“General error: 1005 Can't create table” Using Laravel Schema Build and Foreign Keys

▼魔方 西西 提交于 2019-11-27 21:03:59

I'm not 100% sure if these are the reasons this is failing but a couple of pointers. If you're using an older version of mySQL as the database, the default table implementation is myISAM that does not support foreign key restraints. As your scripts are failing on the foreign key assignment, you are better off explicitly stating that you want INNODB as the engine using this syntax in Schema's create method.

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

    $table->increments('id');
    $table->string('title')->nullable();
    $table->string('summary')->nullable();
    $table->timestamps();
});

This should hopefully alleviate the problems you are having.

Also, whilst you can declare foreign keys as an afterthought, I create the foreign keys within the initial schema as I can do an easy check to make sure I've got the right DB engine set.

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

    $table->increments('id');
    $table->integer('author');
    $table->integer('lesson');
    $table->string('title')->nullable();
    $table->string('summary')->nullable();
    $table->string('tagline')->nullable();
    $table->text('content')->nullable();
    $table->text('attachments')->nullable();
    $table->timestamps();

    $table->foreign('author')->references('id')->on('users');
    $table->foreign('lesson')->references('id')->on('lessons');
});

Hope this helps / solves your problem.

I've been having the same problem. I just noticed the following note at the very bottom of the Laravel Schema docs:

Note: The field referenced in the foreign key is very likely an auto increment and therefore automatically an unsigned integer. Please make sure to create the foreign key field with unsigned() as both fields have to be the exact same type, the engine on both tables has to be set to InnoDB, and the referenced table must be created before the table with the foreign key.

For me, as soon as I set my foreign key fields as such:

$table->integer('author')->unsigned();

I had no problem.

EDIT: Also, make sure that the fields in the foreign table are already created, otherwise this may fail with the same error.

Tim Ogilvy

A Summary of the answers already listed, plus mine:

  1. Foreign Keys generally require InnoDb, so set your default engine, or explicitly specify

    $table->engine = 'InnoDB';
    
  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).

I ran into this issue too.

The solution I found is that the tables that contain the id that is being used a foreign id needs to be created before another table can reference it. Basically, you are creating a table and telling MySQL to reference another table's primary key but that table doesn't exist yet.

In your example, the author and lesson tables need to be created first.

The order in which the tables are created is dependent on artisan and the order you created your migration files.

My opinion would be to empty out your database of all the tables and change the timestamps in the migration file names (or delete them and recreate them in the correct order) so that your author and lesson tables are created before your tutorials table.

I received the same error because I forgot to set the table type to InnoDB on the referenced table:

$table->engine = 'InnoDB';
Nima Ghaedsharafi

Laravel5, MySQL55, CentOS65

in my case the errors were same as this.

Error: [Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table 'nabsh.#sql-5b0_e' (errno: 121) (SQL: alter table usermeta add constraint usermeta_uid_foreign foreign key (uid) ref erences users (id) on delete cascade).

I found a good tip in this problem's approved answer: ERROR: Error 1005: Can't create table (errno: 121)

Tip: You will get this message if you're trying to add a constraint with a name that's already used somewhere else.

in my case this error means the constraint which has been tried to add is already exists somewhere (but i couldn't see them anywhere).

I copied the output error query and execute it within sequel pro, then hopefully I saw the same error again. as the tip says I changed the constraint name to something else then it affected with no error so there's a problem with constraint name builder in laravel5 + MySQL55 + CentOS65.

Solution: try to rename constraints by sending the second parameter at foreign method in table schema.

Schema::table('tutorials', function($table)
{
    $table->foreign('author')->references('id')->on('users');
    $table->foreign('lesson')->references('id')->on('lessons');
});

to ->

Schema::table('tutorials', function($table)
{
    $table->foreign('author', 'fk_tutorials_author')->references('id')->on('users');
    $table->foreign('lesson', 'fk_tutorials_lesson')->references('id')->on('lessons');
});

i hope it helps. it works in my case

This happened to me in Yii Framework 1.x migrations too. Turned out that similarily to the Laravel solutions above it may be caused by a

  • wrong spelled (or not yet existing) table name
  • wrong spelled (or not yet existing) column name
  • duplicate foreign key name in the same database being used in different tables
Guka Gunia

when using foreign key-s make sure that your foreign key is unsigned. this worked for me

Easiest way is to disable foreign key checks:

DB::statement('set foreign_key_checks=0');

Schema::table( ... );

DB::statement('set foreign_key_checks=1');

Here's what I do in Laravel 5:

// CREATING TABLE
Schema::create('your_table_name', function (Blueprint $table) {
    $table->engine = 'InnoDB';
    $table->increments('id'); // index field example sample
    $table->string('field2'); // some varchar/string field sample
    $table->integer('field3'); // some integer field sample
    $table->integer('field_some_table_id')->unsigned; //for field that contains foreign key constraint
});

// FOREIGN KEY CONSTRAINT
Schema::table('stock', function ($table) {
    $table->foreign('field_some_table_id')->references('id')->on('some_table')->onDelete('cascade')->onUpdate('cascade');
});

That's all for the conclusion, and it works for me.

Nina

You have to give the integer an unsigned flag in Laravel 5.4, like this:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('post_id');
        $table->text('title');
        $table->text('text');
        $table->integer('employee_post_id_number')->unsigned();
        $table->foreign('employee_post_id_number')->references 
        ('employee_id_number')->on('employees');
        $table->timestamps();
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!