php - SQLSTATE[HY000] : General error: 1364 Field 'parent_id' doesn't have a default value

标签 php laravel

我正在构建自己的论坛作为练习,我设置了具有多态关系的TopicComment模型,一条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/

相关文章:

php - 绕过 eval() T_USE 解析错误

validation - Laravel 验证 - 输入必须是数组中的项目之一

laravel - Laravel:如何在PhpUnit上启用stacktrace错误

php - Laravel 路由变量,foreach

php - CI 访问接口(interface)上的属性

php - 删除 WordPress 网址中的类别

php - PHP App在localhost上完美运行,在任何Web服务器上完全失败,并出现一些奇怪的错误

php - jquery ajax使用php json编码获取数据库结果

php - 为动态行应用样式表类

php - SQL - 您的 SQL 语法有错误吗?