Commit 467949f7 authored by Maxim Lanin's avatar Maxim Lanin Committed by Jens Segers

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
parent 4e6cc229
...@@ -179,6 +179,10 @@ class BelongsToMany extends EloquentBelongsToMany ...@@ -179,6 +179,10 @@ class BelongsToMany extends EloquentBelongsToMany
// Attach the new parent id to the related model. // Attach the new parent id to the related model.
$model->push($this->foreignKey, $this->parent->getKey(), true); $model->push($this->foreignKey, $this->parent->getKey(), true);
} else { } else {
if ($id instanceof Collection) {
$id = $id->modelKeys();
}
$query = $this->newRelatedQuery(); $query = $this->newRelatedQuery();
$query->whereIn($this->related->getKeyName(), (array) $id); $query->whereIn($this->related->getKeyName(), (array) $id);
......
...@@ -291,6 +291,18 @@ class RelationsTest extends TestCase ...@@ -291,6 +291,18 @@ class RelationsTest extends TestCase
$this->assertCount(2, $user->clients); $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() public function testBelongsToManySyncAlreadyPresent()
{ {
$user = User::create(['name' => 'John Doe']); $user = User::create(['name' => 'John Doe']);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment