Skip to content

Commit

Permalink
Fix BelongsToMany with custom $relatedKey (#25221)
Browse files Browse the repository at this point in the history
  • Loading branch information
staudenmeir authored and taylorotwell committed Aug 24, 2018
1 parent e0cf3df commit 65a82db
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,7 @@ public function save(Model $model, array $pivotAttributes = [], $touch = true)
{
$model->save(['touch' => false]);

$this->attach($model->getKey(), $pivotAttributes, $touch);
$this->attach($model, $pivotAttributes, $touch);

return $model;
}
Expand Down Expand Up @@ -790,7 +790,7 @@ public function create(array $attributes = [], array $joining = [], $touch = tru
// accomplish this which will insert the record and any more attributes.
$instance->save(['touch' => false]);

$this->attach($instance->getKey(), $joining, $touch);
$this->attach($instance, $joining, $touch);

return $instance;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -464,11 +464,11 @@ public function withPivot($columns)
protected function parseIds($value)
{
if ($value instanceof Model) {
return [$value->getKey()];
return [$value->{$this->relatedKey}];
}

if ($value instanceof Collection) {
return $value->modelKeys();
return $value->pluck($this->relatedKey)->all();
}

if ($value instanceof BaseCollection) {
Expand Down
24 changes: 24 additions & 0 deletions tests/Integration/Database/EloquentBelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,24 @@ public function can_touch_related_models()

$this->assertNotEquals('2017-10-10 10:10:10', Tag::find(300)->updated_at);
}

public function test_custom_related_key()
{
$post = Post::create(['title' => str_random()]);

$tag = $post->tagsWithCustomRelatedKey()->create(['name' => str_random()]);
$this->assertEquals($tag->name, $post->tagsWithCustomRelatedKey()->first()->pivot->tag_id);

$post->tagsWithCustomRelatedKey()->detach($tag);

$post->tagsWithCustomRelatedKey()->attach($tag);
$this->assertEquals($tag->name, $post->tagsWithCustomRelatedKey()->first()->pivot->tag_id);

$post->tagsWithCustomRelatedKey()->detach(new Collection([$tag]));

$post->tagsWithCustomRelatedKey()->attach(new Collection([$tag]));
$this->assertEquals($tag->name, $post->tagsWithCustomRelatedKey()->first()->pivot->tag_id);
}
}

class Post extends Model
Expand Down Expand Up @@ -619,6 +637,12 @@ public function tagsWithCustomAccessor()
->using(CustomPivot::class)
->as('tag');
}

public function tagsWithCustomRelatedKey()
{
return $this->belongsToMany(Tag::class, 'posts_tags', 'post_id', 'tag_id', 'id', 'name')
->withPivot('flag');
}
}

class Tag extends Model
Expand Down

0 comments on commit 65a82db

Please sign in to comment.