Skip to content

Commit 191ba31

Browse files
nunntomTom Nunn
andauthored
fix(database): prevent infinite loop when creating a model with a HasOne relationship (#1962)
Co-authored-by: Tom Nunn <tnunn@emovia.net>
1 parent 1048103 commit 191ba31

2 files changed

Lines changed: 23 additions & 2 deletions

File tree

packages/database/src/Builder/QueryBuilders/InsertQueryBuilder.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -293,11 +293,12 @@ private function handleStandardHasOneRelation(HasOne $hasOne, object|array $rela
293293
}
294294

295295
// TODO: we might need to bake this into the naming strategy class
296-
$foreignKeyColumn = Intl\singularize_last_word($ownerModel->getTableName()) . '_' . $ownerModel->getPrimaryKey();
296+
$foreignKeyProperty = Intl\singularize_last_word($ownerModel->getTableName());
297+
$foreignKeyColumn = $foreignKeyProperty . '_' . $ownerModel->getPrimaryKey();
297298

298299
$preparedData = is_array($relation)
299300
? [...$relation, ...[$foreignKeyColumn => $parentId->value]]
300-
: [...$this->convertObjectToArray($relation), ...[$foreignKeyColumn => $parentId->value]];
301+
: [...$this->convertObjectToArray($relation, [$foreignKeyProperty]), ...[$foreignKeyColumn => $parentId->value]];
301302

302303
$relatedModelQuery = new InsertQueryBuilder(
303304
model: $hasOne->property->getType()->asClass(),

tests/Integration/Database/Builder/IsDatabaseModelTest.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,26 @@ public function test_all_with_relations(): void
184184
$this->assertEquals(1, $book->author->id->value);
185185
}
186186

187+
public function test_create_with_hasone_relation(): void
188+
{
189+
$this->database->migrate(
190+
CreateMigrationsTable::class,
191+
CreatePublishersTable::class,
192+
CreateAuthorTable::class,
193+
CreateBookTable::class,
194+
CreateIsbnTable::class,
195+
);
196+
197+
$book = Book::create(
198+
title: 'Book Title',
199+
isbn: Isbn::new(value: '123-456-789'),
200+
);
201+
202+
$book = Book::findById($book->id)->load('isbn');
203+
204+
$this->assertSame('123-456-789', $book->isbn->value);
205+
}
206+
187207
public function test_missing_relation_exception(): void
188208
{
189209
$this->database->migrate(

0 commit comments

Comments
 (0)