Develeone
Develeone

Reputation: 73

Laravel migration: adding foreign key to the same table where ID is a string

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.

Upvotes: 7

Views: 7597

Answers (1)

SEYED BABAK ASHRAFI
SEYED BABAK ASHRAFI

Reputation: 4271

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

Upvotes: 25

Related Questions