I'm reading the tutorial* on how to define many-to-many polymorphic relationships in Laravel but it doesn't show how to save records with this relationship.
In the their example they have
class Post extends Model
{
/**
* Get all of the tags for the post.
*/
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
and
class Tag extends Model
{
/**
* Get all of the posts that are assigned this tag.
*/
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
/**
* Get all of the videos that are assigned this tag.
*/
public function videos()
{
return $this->morphedByMany('App\Video', 'taggable');
}
}
I've tried saving in different ways but the attempts that makes most sense to me is:
$tag = Tag::find(1);
$video = Video::find(1);
$tag->videos()->associate($video);
or
$tag->videos()->sync($video);
None of these are working. Can anyone give me a clue on what I could try?
A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.
with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.
BelongsTo relationship in laravel is used to create the relation between two tables. belongsTo means create the relation one to one in inverse direction or its opposite of hasOne. For example if a user has a profile and we wanted to get profile with the user details then we can use belongsTo relationship.
It's simple like that, see this section.
Instead of manually setting the attribute on the videos, you may insert the Comment directly from the relationship's save method:
//Create a new Tag instance (fill the array with your own database fields) $tag = new Tag(['name' => 'Foo bar.']); //Find the video to insert into a tag $video = Video::find(1); //In the tag relationship, save a new video $tag->videos()->save($video);
you missed a step in the associate method, use this:
$tag->videos()->associate($video)->save();
You can also try this which worked for me (morphMany):
$rel_data = ['assigned_type'=>'User','assigned_id'=>$user_model->getKey()];
$event->assigned_models()->create($rel_data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With