Laravel:Eloquent 模型中的多个多态关系
Laravel: Multiple Polymorphic relationships in a Eloquent Model
我有一个 Table 具有以下结构的命名评论
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->morphs('commentable');
$table->morphs('creatable');
$table->text('comment');
$table->timestamps();
});
Eloquent 文件
class Comment extends Model
{
public $fillable = ['comment'];
public function commentable()
{
return $this->morphTo();
}
public function creatable()
{
return $this->morphTo();
}
}
我有两个多态关系
commentable
任何 Article/Post 或视频
creatable
评论作者User/Admin
如何对用户创建的 Post 添加评论?
我尝试使用以下代码创建
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()
:
public function addComment($creatable, $comment)
{
$this->comments()->make(['comment' => $comment])
->creatable()->associate($creatable)
->save();
}
我有一个 Table 具有以下结构的命名评论
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->morphs('commentable');
$table->morphs('creatable');
$table->text('comment');
$table->timestamps();
});
Eloquent 文件
class Comment extends Model
{
public $fillable = ['comment'];
public function commentable()
{
return $this->morphTo();
}
public function creatable()
{
return $this->morphTo();
}
}
我有两个多态关系
commentable
任何 Article/Post 或视频
creatable
评论作者User/Admin
如何对用户创建的 Post 添加评论?
我尝试使用以下代码创建
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()
:
public function addComment($creatable, $comment)
{
$this->comments()->make(['comment' => $comment])
->creatable()->associate($creatable)
->save();
}