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..e0a734acc 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']);