Laravel - Lots of polymorphic relationships with extra fields

How to define many, many polymorphic relationships with additional fields?

I have three (or more, since this is a polymorphic relation).

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

user_id in the marked table refers to the users table by column identifier. 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 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 integrity constraint for lack of user_id:

SQLSTATE [23000]: Violation of integrity constraint: 1452 Unable to add or update child row: foreign key constraint fails with error ( hb . Tagged, CONSTRAINT tagged_user_id_foreign FOREIGN KEY ( user_id ) LINKS users ( id )) (SQL: insert into the values tagged ( tag_id , taggable_id , taggable_type )) (26, 2, App \ Resource)). This was somewhat expected since I never had the opportunity to define or declare a user_id field.

In addition, I tried with the Pivot () relation on tags as follows, to no avail:

 public function tags() { return $this->morphToMany('App\Tag', 'taggable','tagged')->withPivot('user_id'); } 
+6
source share
1 answer

As in the comment: withPivot has nothing to do with saving/creating . If you want to pass additional summary data to saving , follow these steps:

 $post->tags()->save($tag, ['user_id' => $userId]); 
+5
source

Source: https://habr.com/ru/post/988072/


All Articles