我正在阅读有关如何在 Laravel 中定义多对多多态关系的教程*,但它没有显示如何使用这种关系保存记录。
在他们的例子中他们有
class Post extends Model
{
/**
* Get all of the tags for the post.
*/
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
}
和
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');
}
}
我尝试过以不同的方式保存,但对我来说最有意义的尝试是:
$tag = Tag::find(1);
$video = Video::find(1);
$tag->videos()->associate($video);
or
$tag->videos()->sync($video);
这些都不起作用。谁能告诉我可以尝试什么?
最佳答案
就这么简单,看this部分。
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);
关于php - 如何在 Laravel 中保存多态关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42950104/