You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

发布评论时触发SQL错误1364:字段'parent_id'无默认值求助

解决SQLSTATE[HY000]: General error: 1364 Field 'parent_id' doesn't have a default value错误

这个错误的核心原因很明确:你的comments表中parent_id字段被定义为必填项(不允许为null,也没有默认值),但在创建顶级评论(非回复类评论)时,你没有给这个字段赋值,导致SQL插入语句缺少该字段的值,触发了数据库约束错误。

下面是具体的修复步骤:

1. 修改parent_id字段允许为空

首先需要调整你的评论表结构,让parent_id字段可以为null(因为顶级评论没有父评论,这个值就应该是null)。

情况1:还未执行过该迁移

直接修改你的2020_09_18_082706_create_comments_table.php迁移文件,在parent_id的定义后加上->nullable():

public function up() {
    Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('parent_id')->unsigned()->nullable(); // 新增nullable()
        $table->text('comment');
        $table->integer('commentable_id')->unsigned();
        $table->string('commentable_type');
        $table->timestamps();
    });
}

然后重新执行迁移:

php artisan migrate

情况2:已经执行过该迁移(生产/开发环境已存在数据)

不要直接修改原迁移文件,而是创建一个新的迁移来修改字段:

php artisan make:migration add_nullable_to_parent_id_in_comments_table

打开生成的新迁移文件,添加字段修改逻辑:

public function up() {
    Schema::table('comments', function (Blueprint $table) {
        $table->integer('parent_id')->unsigned()->nullable()->change();
    });
}

public function down() {
    Schema::table('comments', function (Blueprint $table) {
        // 回滚时恢复为非空(可选)
        $table->integer('parent_id')->unsigned()->nullable(false)->change();
    });
}

执行迁移:

php artisan migrate

2. 验证现有代码逻辑

你的现有代码逻辑已经是正确的,只需要确保字段允许为空即可:

  • 顶级评论(store方法):不需要设置parent_id,字段允许为空后会自动填充为null,符合Post模型中comments关联的whereNull('parent_id')过滤条件。
  • 回复评论(replyStore方法):你已经正确设置了$reply->parent_id = $request->get('comment_id');,这部分逻辑无需修改。

额外优化建议

如果需要更严谨的数据约束,可以给parent_id添加外键关联到comments.id,确保回复的父评论确实存在:
在迁移文件中添加:

$table->foreign('parent_id')->references('id')->on('comments')->onDelete('cascade');

这样当父评论被删除时,所有子回复也会被级联删除,避免出现孤立的回复数据。

内容的提问来源于stack exchange,提问作者David Kirakosyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 12:57:40