3

I have the following migration :

Schema::create('tags', function (Blueprint $table) {
            $table->increments('id')->unsigned()->index();
            $table->string('name',30);
            $table->integer('parent_id')->nullable();
            $table->string('image_url');
            $table->string('image_id',50);
            $table->timestamps();

            $table->foreign('parent_id')
                  ->references('id')->on('tags')
                  ->onDelete('cascade');
        });

The following issue comes up:

 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alte  
  r table `tags` add constraint `tags_parent_id_foreign` foreign key (`parent_id`) references `tags` (`id`) on delete cascade)

Everything is good. I have checked alot but not working.

The following question is not working for me. I don't know why, That question is not addressing my issues.

StackOverFlow Question

Community
  • 1
  • 1
Gammer
  • 5,453
  • 20
  • 78
  • 121
  • Possible duplicate of [Laravel migration self referencing foreign key issue](http://stackoverflow.com/questions/18427391/laravel-migration-self-referencing-foreign-key-issue) – Samsquanch May 20 '16 at 13:20

2 Answers2

2
$table->increments('id')

Is a shortcut for the column type integer->unsigned

Basically you are trying to link an integer unsigned to an integer so mysql won't let you because values ranges don't match (positive only integer vs all integers)

If you change your code to this:

$table->integer('parent_id')->unsigned()->nullable();

Then mysql will see that both sides of the relation have the same value type (value range of all positive integer on both sides) so the relation is correct.

As a side note and for thoses wondering, a relation can be nullable on none, one or both sides of the relation because nullable is a constraint, not a type.

Atrakeur
  • 4,126
  • 3
  • 17
  • 22
1

Foreign key types have to match the type of field they reference. You have your 'id' as unsigned, but the foreign key field is not.

lagbox
  • 48,571
  • 8
  • 72
  • 83