繁体   English   中英

SQLSTATE[HY000]:一般错误:1364 字段“parent_id”没有默认值

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

我正在建立自己的论坛作为练习,我设置了具有多态关系的TopicComment模型, comment可以属于一个topic或另一个comment ,这是因为我想要嵌套评论。 另一个问题是当我回复该主题时,我收到以下错误:

SQLSTATE[HY000]:一般错误:1364 字段“parent_id”没有默认值(SQL:插入commentsuser_idbodycommentable_idcommentable_typeupdated_atcreated_at )值(1 <\p>ljlnlnlnlnlnllnlnlnlnlnln</p >, 1, App\Models\Topic, 2019-11-08 20:41:43, 2019-11-08 20:41:43))

我的模型和迁移。

主题 model:

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();
    });
}

评论 model:

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列没有值(您没有设置值,也没有默认值)。 将列设置为nullable ,或传递parent_id

migration中:

$table->integer('parent_id')->unsigned()->nullable();

由于对主题的评论没有父评论(不是回复),因此parent_id将是 null,但是您的数据库架构不允许它,使列可为空

$table->integer('parent_id')->unsigned()->nullable();

或者给它null作为默认值

$table->unsignedInteger('parent_id')->default(null);

希望这可以帮助

我遇到了这个问题并通过将我的列添加到可填充属性中来解决

将 parent_id 添加到 model注释中的可填充数组中,以允许通过 create 和 mass 方法保存

protected $fillable = ['parent_id'];

我正在尝试使用 laravel 将数据插入数据库,这给了我这个错误 Illuminate \ Database \ QueryException (HY000) SQLSTATE[HY000]:一般错误:1364 字段“正文”没有默认值(SQL:插入categoriesid , title , updated_at , created_at ) 值 (1, khan, 2019-11-09 13:14:21, 2019-11-09 13:14:21))。 请指导我该怎么做

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM