我正在构建自己的论坛作为练习,我设置了具有多态关系的Topic
和Comment
模型,一条comment
可以属于一个主题
或另一个评论
,这是因为我想要嵌套评论。另一个问题是当我回复该主题时出现以下错误:
SQLSTATE[HY000]: General error: 1364 Field 'parent_id' doesn't have a default value (SQL: insert into
comments
(user_id
,body
,commentable_id
,commentable_type
,updated_at
,created_at
) values (1 <\p>ljlnlnlnlnlnllnlnlnlnlnln</p>, 1, App\Models\Topic, 2019-11-08 20:41:43, 2019-11-08 20:41:43))
我的模型和迁移。
主题模型:
class Topic extends Model
{
protected $table = 'topics';
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable')->whereNull('parent_id');
}
}
public function up()
{
Schema::create('topics', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id')->index();
$table->foreign('user_id')->references('id')->on('users');
$table->string('title');
$table->text('body');
$table->string('url')->unique();
$table->string('slug')->unique();
$table->boolean('isVisible')->default(false);
$table->timestamps();
});
}
评论模型:
class Comment extends Model
{
protected $table = 'comments';
public function author()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function replies()
{
return $this->hasMany('App\Models\Comment', 'parent_id');
}
}
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->integer('parent_id')->unsigned();
$table->integer('commentable_id')->unsigned();
$table->string('commentable_type');
$table->text('body');
$table->timestamps();
});
}
最佳答案
这个错误非常明显; parent_id
列没有值(您没有设置值,也没有默认值)。将列设置为可为空
,或传递parent_id
在迁移
中:
$table->integer('parent_id')->unsigned()->nullable();
关于php - SQLSTATE[HY000] : General error: 1364 Field 'parent_id' doesn't have a default value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58773137/