Gabotronix
1 week ago

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

Posted 1 week ago by Gabotronix

Hi everybody, I'm building my own forum as practice, I set up Topic and Comment models with polymorphic relationship, a comment can belong to a topic or another comment, this is because I want to have nested comments. Another issue is when I reply to the topic I get the following error:

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))

My models and Migrations.

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


}

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

Please sign in or create an account to participate in this conversation.