Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.8] Make updateExistingPivot() safe on non-existent pivot #29362

Merged
merged 1 commit into from
Aug 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -220,12 +220,12 @@ public function updateExistingPivot($id, array $attributes, $touch = true)
*/
protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch)
{
$updated = $this->getCurrentlyAttachedPivots()
$pivot = $this->getCurrentlyAttachedPivots()
->where($this->foreignPivotKey, $this->parent->{$this->parentKey})
->where($this->relatedPivotKey, $this->parseId($id))
->first()
->fill($attributes)
->isDirty();
->first();

$updated = $pivot ? $pivot->fill($attributes)->isDirty() : false;

$this->newPivot([
$this->foreignPivotKey => $this->parent->{$this->parentKey},
Expand Down
35 changes: 35 additions & 0 deletions tests/Integration/Database/EloquentBelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,33 @@ public function test_custom_pivot_class_using_sync()
$this->assertNotEmpty($results['detached']);
}

public function test_custom_pivot_class_using_update_existing_pivot()
{
Carbon::setTestNow('2017-10-10 10:10:10');

$post = Post::create(['title' => Str::random()]);
$tag = TagWithCustomPivot::create(['name' => Str::random()]);

DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'],
]);

// Test on actually existing pivot
$this->assertEquals(
1,
$post->tagsWithCustomExtraPivot()->updateExistingPivot($tag->id, ['flag' => 'exclude'])
);
foreach ($post->tagsWithCustomExtraPivot as $tag) {
$this->assertEquals('exclude', $tag->pivot->flag);
}

// Test on non-existent pivot
$this->assertEquals(
0,
$post->tagsWithCustomExtraPivot()->updateExistingPivot(0, ['flag' => 'exclude'])
);
}

public function test_attach_method()
{
$post = Post::create(['title' => Str::random()]);
Expand Down Expand Up @@ -776,6 +803,14 @@ public function tagsWithCustomPivot()
->withTimestamps();
}

public function tagsWithCustomExtraPivot()
{
return $this->belongsToMany(TagWithCustomPivot::class, 'posts_tags', 'post_id', 'tag_id')
->using(PostTagPivot::class)
->withTimestamps()
->withPivot('flag');
}

public function tagsWithCustomPivotClass()
{
return $this->belongsToMany(TagWithCustomPivot::class, PostTagPivot::class, 'post_id', 'tag_id');
Expand Down