如何在拉拉维尔的多态关系中保存?

2022-08-30 14:33:10

我正在阅读有关如何在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);

这些都不起作用。任何人都可以给我一个关于我可以尝试什么的线索吗?


答案 1

就这么简单,请参阅部分。

您可以直接从关系的保存方法插入 Comment,而不是手动设置视频的属性:

//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);

答案 2

您错过了关联方法中的步骤,请使用以下命令:

$tag->videos()->associate($video)->save();

推荐