Search code examples
laravelmigrationkey

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.


Solution

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