如何在Laravel中保存多态关系?

Dub*_*bby 10 php polymorphism orm laravel

我正在阅读有关如何在Laravel中定义多对多多态关系的教程*,但它没有说明如何使用这种关系保存记录.

在他们的例子中他们有

class Post extends Model
{
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }
}
Run Code Online (Sandbox Code Playgroud)

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试过以不同的方式保存,但对我来说最有意义的尝试是:

$tag = Tag::find(1);
$video = Video::find(1);
$tag->videos()->associate($video);

or

$tag->videos()->sync($video);
Run Code Online (Sandbox Code Playgroud)

这些都不起作用.谁能给我一些我可以尝试的线索?

Joã*_*ani 19

这很简单,请参阅节.

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

//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);
Run Code Online (Sandbox Code Playgroud)


小智 12

您错过了 Associate 方法中的一个步骤,请使用以下命令:

$tag->videos()->associate($video)->save();
Run Code Online (Sandbox Code Playgroud)