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

标签 php laravel orm polymorphism

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

相关文章:

php - 使用 mysql 和 php 从虚拟值回显 AVG 值

php - 如何使用转义字符拆分以空格分隔的 token 字符串?

javascript - Ajax 请求时出现 500 内部服务器错误。不确定问题的根源

php - Container.php 第 776 行中的 ReflectionException : Class APPPATH\Http\Controllers\DashboardController does not exist

jpa - 无法解析显式命名的映射文件 : com/orm/Sample-orm. xml : origin(com/orm/Sample-orm. xml)

java - 尝试使用 @ManyToOne 映射来持久化实体

javascript - 为什么 jQuery.cookie 插件返回 “[object Object]”

php - 降序排列

php - RouteCollection.php 第 219 行中的 MethodNotAllowedHttpException

java - 如何通过 Hibernate 对数据库列的任何读/写访问调用 Java 方法