Skip to content

Commit 467949f

Browse files
mlaninjenssegers
authored andcommitted
Fix collections attachments. (#889)
* Fix collections attachments. If you will try to attach model simultaneously to a collection of related models, you'll crash your app, because this method will try to operate with models themselves but not with their ids. This change considers every case and fixes collections relations. * Fix typo
1 parent 4e6cc22 commit 467949f

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/Jenssegers/Mongodb/Relations/BelongsToMany.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,10 @@ public function attach($id, array $attributes = [], $touch = true)
179179
// Attach the new parent id to the related model.
180180
$model->push($this->foreignKey, $this->parent->getKey(), true);
181181
} else {
182+
if ($id instanceof Collection) {
183+
$id = $id->modelKeys();
184+
}
185+
182186
$query = $this->newRelatedQuery();
183187

184188
$query->whereIn($this->related->getKeyName(), (array) $id);

tests/RelationsTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,18 @@ public function testBelongsToManyAttachArray()
291291
$this->assertCount(2, $user->clients);
292292
}
293293

294+
public function testBelongsToManyAttachEloquentCollection()
295+
{
296+
$user = User::create(['name' => 'John Doe']);
297+
$client1 = Client::create(['name' => 'Test 1']);
298+
$client2 = Client::create(['name' => 'Test 2']);
299+
$collection = new \Illuminate\Database\Eloquent\Collection([$client1, $client2]);
300+
301+
$user = User::where('name', '=', 'John Doe')->first();
302+
$user->clients()->attach($collection);
303+
$this->assertCount(2, $user->clients);
304+
}
305+
294306
public function testBelongsToManySyncAlreadyPresent()
295307
{
296308
$user = User::create(['name' => 'John Doe']);

0 commit comments

Comments
 (0)