niko craft
niko craft

Reputation: 2977

General error 1215 while trying to make a foreign key within the same table, integer to integer

I am trying to make a foreign key in the same table and no matter what I test I get an error.

In Connection.php line 647:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table trip_tags add constraint trip_tags_parent_foreign foreign key (parent) refer ences trip_tags (id) on delete cascade)

In Connection.php line 449:

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

This is my code

    Schema::create('trip_tags', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->uuid('uuid')->unique();
        $table->integer('id')->unsigned();
        $table->string('name')->nullable();
        $table->integer('parent')->unsigned()->nullable();

        $table->timestamps();
    });

    Schema::table('trip_tags', function (Blueprint $table) {

        $table->foreign('parent')
            ->references('id')
            ->on('trip_tags')
            ->onDelete('cascade');
    });

I try to point parent to id, both are unsigned integers, I guess the reason that creating the foreign key fails is that they are not compatible in some way, I cant figure out what is wrong.

I tried to point parent to uuid but then had to make it a string and that worked. But I have to have the parent point to id which is integer and I cant get it to migrate withour error.

Upvotes: 0

Views: 228

Answers (1)

DevK
DevK

Reputation: 9942

It's because your id column doesn't have an index on it.

Add ->unique() to the declaration:

$table->integer('id')->unsigned()->unique();

Upvotes: 2

Related Questions