Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreign keys in Laravel 4 migrations issue

I've just created a new Laravel 4 project and am finding strange things happening with the foreign key aspect of the schema builder. If I use the ->foreign() method in any of my migrations I get thrown MySQL errors 150 and general error 1005. According to the documentation at laravel.com/docs the two scenario's at the bottom should work? Anyone know why they don't?

The following does work:

    Schema::create('areas', function($table)
    {
        $table->engine ='InnoDB';
        $table->increments('id');

        $table->integer('region_id')->references('id')->on('regions');

        $table->string('name', 160);
        $table->timestamps();
    });

But these two do not work:

    Schema::create('areas', function($table)
    {
        $table->engine ='InnoDB';
        $table->increments('id');

        $table->foreign('region_id')->references('id')->on('regions');

        $table->string('name', 160);
        $table->timestamps();
    });

    Schema::create('areas', function($table)
    {
        $table->engine ='InnoDB';
        $table->increments('id');

        $table->integer('region_id');
        $table->foreign('region_id')->references('id')->on('regions');

        $table->string('name', 160);
        $table->timestamps();
    });
like image 410
JasonMortonNZ Avatar asked Sep 11 '25 10:09

JasonMortonNZ


2 Answers

Check your id type. Laravel 4 creates an incremental id with a int(10) unsigned. If you create a basic integer and try to put a foreign key on it, it will fail.

As suggested in the documentation at this link, you should create the foreign id with $table->unsignedInteger(YOUR_ID_NAME); to make it work.

like image 110
netvision73 Avatar answered Sep 13 '25 02:09

netvision73


Also some answers over at this question "General error: 1005 Can't create table" Using Laravel Schema Build and Foreign Keys

A Summary of the answers listed there, including mine:

  1. Foreign Keys generally require InnoDb, so set your default engine, or explicitly specify $table->engine = 'InnoDB'; If your table is already created and has defaulted to MyISAM, you may need to alter it.

  2. Foreign keys require the referenced table to exist. Make sure the referenced table is created in an earlier migration, prior to creating the key. Consider creating the keys in a separate migration to be sure.

  3. Foreign Keys require the data type to be congruent. Check whether the referenced field is the same type, whether its signed or unsigned, whether it's length is the same (or less).

  4. If you are switching between hand coding migrations, and using generators, make sure you check the id type you are using. Artisan uses increments() by default but Jeffrey Way appears to prefer integer('id', true).

like image 37
Tim Ogilvy Avatar answered Sep 13 '25 01:09

Tim Ogilvy