Skip to content

Commit 035d704

Browse files
authored
Check if $primaryKey is present before execute unset (#2599)
Problem: Previously, while executing a dissociate operation on Embed Models in MongoDB, an Exception was thrown that prevented the removal of Models. This happened specifically when a Model in the list lacked a $propertyKey. Solution: Add a validation check to the dissociate operation for Embed Models in MongoDB. With this fix, the application will now verify if a propertyKey is present in each Model in the list before proceeding with the removal. This resolves the issue of an Exception being thrown during the operation.
1 parent 2ea9f7a commit 035d704

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

src/Relations/EmbedsMany.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ public function dissociate($ids = [])
152152

153153
// Remove the document from the parent model.
154154
foreach ($records as $i => $record) {
155-
if (in_array($record[$primaryKey], $ids)) {
155+
if (array_key_exists($primaryKey, $record) && in_array($record[$primaryKey], $ids)) {
156156
unset($records[$i]);
157157
}
158158
}

tests/EmbeddedRelationsTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,21 @@ public function testEmbedsManyDissociate()
310310
$freshUser = User::find($user->id);
311311
$this->assertEquals(0, $user->addresses->count());
312312
$this->assertEquals(1, $freshUser->addresses->count());
313+
314+
$broken_address = Address::make(['name' => 'Broken']);
315+
316+
$user->update([
317+
'addresses' => array_merge(
318+
[$broken_address->toArray()],
319+
$user->addresses()->toArray()
320+
),
321+
]);
322+
323+
$curitiba = $user->addresses()->create(['city' => 'Curitiba']);
324+
$user->addresses()->dissociate($curitiba->id);
325+
326+
$this->assertEquals(1, $user->addresses->where('name', $broken_address->name)->count());
327+
$this->assertEquals(1, $user->addresses->count());
313328
}
314329

315330
public function testEmbedsManyAliases()

0 commit comments

Comments
 (0)