Skip to content

Commit

Permalink
Add tests for updating existing pivot + add option for passing model
Browse files Browse the repository at this point in the history
  • Loading branch information
bobbybouwmann committed Mar 14, 2018
1 parent bcbeb69 commit a05ee88
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public function updateExistingPivot($id, array $attributes, $touch = true)
$attributes = $this->addTimestampsToAttachment($attributes, true);
}

$updated = $this->newPivotStatementForId($id)->update(
$updated = $this->newPivotStatementForId($this->parseId($id))->update(
$this->castAttributes($attributes)
);

Expand Down Expand Up @@ -488,6 +488,21 @@ protected function parseIds($value)
return (array) $value;
}

/**
* Get the ID from the given mixed value.
*
* @param mixed $value
* @return mixed
*/
protected function parseId($value)
{
if ($value instanceof Model) {
return $value->getKey();
}

return $value;
}

/**
* Cast the given keys to integers if they are numeric and string otherwise.
*
Expand Down
44 changes: 44 additions & 0 deletions tests/Integration/Database/EloquentBelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,44 @@ public function can_touch_related_models()

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

/**
* @test
*/
public function can_update_existing_pivot()
{
$tag = Tag::create(['name' => str_random()]);
$post = Post::create(['title' => str_random()]);

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

$post->tagsWithExtraPivot()->updateExistingPivot($tag->id, ['flag' => 'exclude']);

foreach ($post->tagsWithExtraPivot as $tag) {
$this->assertEquals('exclude', $tag->pivot->flag);
}
}

/**
* @test
*/
public function can_update_existing_pivot_using_model()
{
$tag = Tag::create(['name' => str_random()]);
$post = Post::create(['title' => str_random()]);

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

$post->tagsWithExtraPivot()->updateExistingPivot($tag, ['flag' => 'exclude']);

foreach ($post->tagsWithExtraPivot as $tag) {
$this->assertEquals('exclude', $tag->pivot->flag);
}
}
}

class Post extends Model
Expand All @@ -601,6 +639,12 @@ public function tags()
->wherePivot('flag', '<>', 'exclude');
}

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

public function touchingTags()
{
return $this->belongsToMany(TouchingTag::class, 'posts_tags', 'post_id', 'tag_id')
Expand Down

0 comments on commit a05ee88

Please sign in to comment.