Laravel Eloquent 一对多的morph没有值的问题

现在有Topic, Post, Comment三个模型, Comment相对Topic和Post是一对多的关系, 也就是说每个Topic和Post都可以有多条Comment.
但现在尝试插入Comment时, 发现并没有插入对应的commentable_idcommentable_type???
报错如下:

SQLSTATE[HY000]: General error: 1364 Field 'commentable_id' doesn't have a default value (SQL: insert into `comments` (`content`, `updated_at`, `created_at`)

App\Models\Comment

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

App\Models\Topic

public function comments()
{
    return $this->morphMany('App\Models\Comment', 'commentable');
}

App\Models\Post

public function comments()
{
    return $this->morphMany('App\Models\Comment', 'commentable');
}

Comments数据表中有$table->morphs('commentable');.

请问问题到底出在哪里?`

阅读 4.7k
2 个回答

comments 表中需要建立 commentable_idcommentable_type字段.如下图所示,其中, commentable_id 用于存放Topic或者Post的 id ,而 commentable_type 用于存放所属模型的类名。

图片描述

你可以仔细看看laravel文档中的多态关联.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题