Laravel:雄辩模型中的多个多态关系

时间:2018-08-31 10:22:28

标签: laravel laravel-5 eloquent laravel-5.2

我有一个名为Comments的表,具有以下结构

Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->morphs('commentable');
$table->morphs('creatable');
$table->text('comment');
$table->timestamps();
});

口才文件

class Comment extends Model
{
    public $fillable = ['comment'];

    public function commentable()
    {
        return $this->morphTo();
    }

    public function creatable()
    {
        return $this->morphTo();
    }
}

我有两个多态关系

commentable用于任何文章/帖子或视频

creatable(评论用户/管理员的评论创建者)

如何对用户创建的帖子添加评论?

我尝试使用以下代码创建

public function addComment($creatable, $comment)
{
        $this->comments()->create(['comment' => $comment, 'creatable' => $creatable]);
}

它确实起作用,我收到以下错误消息

Illuminate/Database/QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'creatable_type' doesn't have a default value (SQL: insert into `post_comments` (`comment`, `commentable_id`, `commentable_type`, `updated_at`, `created_at`) values (Test Comment, 1, App/Post, 2018-08-31 10:29:14, 2018-08-31 10:29:14))'

提前谢谢!

1 个答案:

答案 0 :(得分:2)

您可以使用make()

public function addComment($creatable, $comment)
{
        $this->comments()->make(['comment' => $comment])
            ->creatable()->associate($creatable)
            ->save();
}