Laravel:Eloquent 模型中的多个多态关系

Aks*_*ale 4 laravel eloquent laravel-5 laravel-5.2

我有一个名为 Comments 的表,其结构如下

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

雄辩的档案

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

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

    public function creatable()
    {
        return $this->morphTo();
    }
}
Run Code Online (Sandbox Code Playgroud)

我有两个多态关系

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

creatable 对于评论用户/管理员的评论创建者

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

我尝试使用以下代码创建

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

它确实有效,我收到以下错误

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

提前致谢!!!

Jon*_*eir 6

您可以使用make()

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