From 5e9c00cccb84656f830a64d010ee756058a2c738 Mon Sep 17 00:00:00 2001 From: Maxim Lanin Date: Thu, 7 Jul 2016 22:07:28 +0300 Subject: [PATCH 1/2] 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. --- src/Jenssegers/Mongodb/Relations/BelongsToMany.php | 4 ++++ tests/RelationsTest.php | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/Jenssegers/Mongodb/Relations/BelongsToMany.php b/src/Jenssegers/Mongodb/Relations/BelongsToMany.php index 2cca88638..37ae75e8d 100644 --- a/src/Jenssegers/Mongodb/Relations/BelongsToMany.php +++ b/src/Jenssegers/Mongodb/Relations/BelongsToMany.php @@ -179,6 +179,10 @@ public function attach($id, array $attributes = [], $touch = true) // Attach the new parent id to the related model. $model->push($this->foreignKey, $this->parent->getKey(), true); } else { + if ($id instanceof Collection) { + $id = $id->modelKeys(); + } + $query = $this->newRelatedQuery(); $query->whereIn($this->related->getKeyName(), (array) $id); diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index 8572d4727..85ce18b14 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -291,6 +291,18 @@ public function testBelongsToManyAttachArray() $this->assertCount(2, $user->clients); } + public function testBelongsToManyAttachEloquentCollection() + { + $user = User::create(['name' => 'John Doe']); + $client1 = Client::create(['name' => 'Test 1']); + $client2 = Client::create(['name' => 'Test 2']); + $collection = new \Illuminate\Database\Eloquent\Collection([$client1, $client2]) + + $user = User::where('name', '=', 'John Doe')->first(); + $user->clients()->attach($collection); + $this->assertCount(2, $user->clients); + } + public function testBelongsToManySyncAlreadyPresent() { $user = User::create(['name' => 'John Doe']); From 9e96daf5938c60ae4086f2e32e294ca899cb4168 Mon Sep 17 00:00:00 2001 From: Maxim Lanin Date: Thu, 7 Jul 2016 23:02:36 +0300 Subject: [PATCH 2/2] Fix typo --- tests/RelationsTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index 85ce18b14..e0a734acc 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -296,7 +296,7 @@ public function testBelongsToManyAttachEloquentCollection() $user = User::create(['name' => 'John Doe']); $client1 = Client::create(['name' => 'Test 1']); $client2 = Client::create(['name' => 'Test 2']); - $collection = new \Illuminate\Database\Eloquent\Collection([$client1, $client2]) + $collection = new \Illuminate\Database\Eloquent\Collection([$client1, $client2]); $user = User::where('name', '=', 'John Doe')->first(); $user->clients()->attach($collection);