我有一个名为“Comments”的表格,其结构如下:
我有两个多态关系:
- `commentable` 可用于任何文章 / 帖子或视频 - `creatable` 仅限于评论创建者,可以是评论用户 / 管理员
如何对用户创建的帖子添加评论?
我尝试使用以下代码创建:
它确实起作用了,我收到了以下错误信息。
提前致谢!
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))'
提前致谢!
Comment
模型应该只有一个方法。此外,如果你想使用默认的多态关联,comments
表格应该具有不同的结构,包括commentable_id
和commentable_type
。再次检查文档。如果我没有弄错的话,你的comments
表格具有比所需更多的字段。 - Tpojka$table->morphs('commentable');
,commentable_id
和commentable_type
将自动添加到表中。@Tpojka - Akshay Khale$table->nullableMorphs('commentable');
和$table->nullableMorphs('creatable');
(允许空值)? - Tpojka