Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Migration issue : Table self relation

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

like image 663
Gammer Avatar asked May 04 '26 23:05

Gammer


1 Answers

$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.

like image 80
Atrakeur Avatar answered May 07 '26 09:05

Atrakeur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!