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

Laravel:雄辩模型中的多重多态关系,laravel,laravel-5,eloquent,laravel-5.2,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 Comme

我有一个名为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();
    }
}
我有两个多态关系

可评论
任何文章/帖子或视频

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

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

我尝试使用以下代码创建

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))'
提前感谢

您可以使用
make()

公共函数addComment($createable,$comment)
{
$this->comments()->make(['comment'=>$comment])
->createable()->associate($createable)
->save();
}

add error and relations in your model Added@J.doe您的
Comment
模型应该只有一种方法。另外,
comments
表应该有不同的结构,包括
commentable\u id
commentable\u type
,如果您想使用默认的多态关系。请再检查一次。如果我没有错的话,您的
comments
表中的字段比需要的多。我的实现与文档中给出的不同,在文档中,它们只处理一个多态关系,在我的情况下,我需要多个<代码>可注释的\u id和
可注释的\u类型
将自动添加到表中。因为
$table->morphs('commentable')
@tpojkano在没有看到表图的情况下说起来很简单,但也许您需要
$table->nullableMorphs('commentable')
$table->nullableMorphs('createable')在表中(允许空值)?我尝试了这段代码,但它不起作用,我甚至在函数开始时尝试了
enableQueryLog()
,最后它返回了
[]
你如何调用
addComment()
$post->addComment($user,“这是我的注释”)
其中
$post
是一个
可评论的
$user
是一个
可创建的
$user
来自数据库(
user::find()
)或新创建的(
new user()
)?来自数据库,使用
find
方法
$user=user::find(1)