Reputation: 806
How can I define a many to many polymorphic relation with extra fields?
I have three (or more, as it is a polymorphic relation) tables.
tags table: id, name
tagged table: id, tag_id, taggable_id, taggable_type, user_id
posts table: id, record, timestamps
users table: id, name, email
The user_id
on the tagged table referes to the users table on column id.
In my Post model I have:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged');
}
and in my Tag model I have:
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable','tagged');
}
Then when I am try this in my controller:
$tag = new \App\Tag(
array(
'tag'=>"someTag"
));
$tag->save()
$post = \App\Post::find($id);
$post->tags()->save($tag);
I get Integrity Constraint Violation for not having a user_id:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (
hb
.tagged
, CONSTRAINTtagged_user_id_foreign
FOREIGN KEY (user_id
) REFERENCESusers
(id
)) (SQL: insert intotagged
(tag_id
,taggable_id
,taggable_type
) values (26, 2, App\Resource)). Which is somewhat expected, as I have never had the chance to define or declare the user_id field.
Also, I have tried withPivot() on tags relation as follows, to no avail:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id');
}
Upvotes: 10
Views: 5484
Reputation: 81167
Like in the comment: withPivot
has nothing to do with saving/creating
. If you want to pass additional pivot data when saving
, do this:
$post->tags()->save($tag, ['user_id' => $userId]);
Upvotes: 10