1
votes

I'm trying to make "categories" migration, where each category refers it's parent category by ID in the same table.

Migration:

    Schema::create('categories', function (Blueprint $table) {
        $table->string('id', 36)->primary();

        $table->string('parent_id', 36)->nullable();
        $table->foreign('parent_id')->references('id')->on('categories');

        $table->string('name');
    });

But i'm getting next error:

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table categories add constraint categories_parent_id_foreign foreign key (parent_id) references categories (id))

Field types are the same, and I don't know, what to do. Removing "->nullable()" has no effect.

Laravel Framework version 6.20.7

Thanks.

1
You have parent table in database?Irshad Khan
Irshad, table are the same, this is one migration for all.Develeone
Unflux, if you told about "$table->foreign('parent_id')->references('id')->on('categories')->nullable();" - no, the same error.Develeone
Welcome to SO ... what version of Laravel btw?lagbox
@lagbox thx, Laravel Framework 6.20.7Develeone

1 Answers

1
votes

Add the foreign key constraint in another run like as below

public function up()
{
    Schema::create('categories', function (Blueprint $table) {
            $table->string('id', 36)->primary();

            $table->string('parent_id', 36)->nullable();

            $table->string('name');
    });

    Schema::table('categories',function (Blueprint $table){
            $table->foreign('parent_id')->references('id')->on('categories');
    });
}