Laravel migration (errno: 150 “Foreign key constraint is incorrectly formed”)

落爺英雄遲暮 提交于 2019-12-04 08:27:51

问题


I have an orders table and a have a sell_shipping_labels which references orders.id as a foreign. However when I run the Laravel migration I get the dreaded error code:

[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table cheapbooks_test.#sql-b5b_b2a (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table sell_shipping_labels add constraint sell_shipping_labels_order_id_foreign foreign key (order_id) references orders (id))

[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table cheapbooks_test.#sql-b5b_b2a (errno: 150 "Foreign key constraint is incorrectly formed")

This is my orders table schema:

   Schema::create('orders', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('book_id');
        $table->integer('status_id');
        $table->double('payment_amount')->nullable();
        $table->timestamp('received_at')->nullable();
        $table->timestamp('paid_at')->nullable();
        $table->timestamps();
        $table->softDeletes();
    });

And this is my sell_shipping_labels schema:

Schema::create('sell_shipping_labels', function (Blueprint $table) {
        $table->increments('id');
        $table->unsignedInteger('order_id');
        $table->string('shippo_object_id');
        $table->string('label_url');
        $table->string('tracking_url');
        $table->string('tracking_number');
        $table->timestamp('arrived_at');
        $table->timestamps();
        $table->softDeletes();

        $table->foreign('order_id')->references('id')->on('orders');
    });
}

Now I've flipped the internet upside down trying to figure out the problem. All of the post about this problem all refer to the fact that the orders table must be created BEFORE the table that has the foreign key on it but this isn't a problem for me because my files are in the correct order.


回答1:


Since increments() creates an unsigned integer column, you need to define the foreign key column as unsigned integer too:

$table->unsignedInteger('order_id');

Or:

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

https://laravel.com/docs/5.5/migrations#foreign-key-constraints




回答2:


the foreign key must be an "unsignedBigInteger" and it will be fixed, something like this:

$table->unsignedBigInteger('user_id');

$table->foreign('user_id')->references('id')->on('users');



回答3:


Primary key and foreign key should be in the same data type.

If the primary key is using unsigned big_integer, the foreign key should also be using unsigned big_integer.

In case laravel 5.8 uses bigIncrements by default when generating new migration (see this pull request), you should make sure that your foreign key is also big_increment or you will get error.

Table users:

Schema::create('users', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');

    ...

}

Table orders:

Schema::create('orders', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');

    ...

    $table->foreign('user_id')->references('id')->on('users');
}

Hope this helps.




回答4:


Laravel 5.8.3 comes with $table->bigIncrements('id');

change it to

$table->increments('id');
$table->integer('order_id')->unsigned();



回答5:


I was also getting the same error. What i was doing in users table is,

$table->unsignedInteger('role_id')->default(2); table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

But i have created the role table after creating users table. So, i edited the role migration file name date before the users table filename date. Like this,

2013_01_22_091213_create_roles_table.php
2014_10_12_000000_create_users_table.php

And finally it works. Maybe sometime you may get this problem. So, i posted it.




回答6:


Check the order of your migrations. If your migrate command is trying to make the sell_shipping_labels table before the orders table this will occur with MySQL. It seems to go on create migration date, oldest to newest. In other words, the order_id on the table it is trying to reference should exist.

I have faced the same problem and I change create migration date.




回答7:


To anyone looking at this using laravel 5.8.x I fixed this by changing this

$table->unsignedInteger('foreign_id');

to this

$table->unsignedBigInteger('foreign_id');

That's due to the use of bigIncrements. You could instead remove chance bigIncrements to increments on both sides of the relation




回答8:


For those which marked answer didn't work:

Check your tables engine. In my case, I was referencing on a MyISAM table in an InnoDB source table. After changing the reference table engine to InnoDB, it worked!




回答9:


  1. Migration files should be created in such a way that the parent migration should come first and the migration file with the foreign key next.
  2. The foreign key and the primary id in the other table should have exactly similar property. If the primary id is increments then make the foreign key integer('xxx_id')->unsigned();



回答10:


I had the same problem and fixed the issue setting the database type to innoDB

The tables created before the migration where 'MyISAM from an legacy system and the migrated are innoDB by default, so the mix of table types were an issue in my case.




回答11:


Most times the reason for this error is usually due to the order of which the migration files are listed or error due to type casting.

Always make sure that the migration of the file which the foreign constraints is to be imposed on comes after the parent migration. And for the latter, make sure its an unsignedBigInteger , although former version of laravel (<5.4) could ignore this type casting error.




回答12:


I faced this problem today. I checked all of suggested solutions such as referenced key and foreign key same datatype, same collation in database engine and laravel config (database.php), date order of migrations and other possibility mistakes, but anyone were my solution! last thing I found was onUpdate and onDelete constraints that put in migrations. By removing them my problem solved!




回答13:


I faced the same problem today. My laravel version is 5.8.29. I solved the problem by doing:

$table->bigIncrements('id'); //current table primary key and id
$table->unsignedBigInteger('user_id'); // foreigh key
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

Hope this works.




回答14:


If the problem is still not solved, try it. you need to create the last associated table.

You should first create orders and after create sell_shipping_labels table

To solve the issue you should rename migration files of Category and Users to date of before Meals Migration file that create those before Meals table.




回答15:


[![enter image description here][1]][1]
public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();


        });
    }

I changed $table->bigIncrements('id') to $table->Increments('id')
For this user_id of files table become same integer type as user table field id. After this command worked.

   public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }



For the second table
 {
        Schema::create('files', function (Blueprint $table) {
            $table->increments('id');

});

            Schema::table('files', function($table) {
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
           });
    }




回答16:


I faced this problem today. My parent table primary key datatype and child table data type was same but error was still there. I have found that my parent and child tables storage engine was different. I have fixed this issue by making both tables storage engine InnoDB from my phpmyadmin.




回答17:


For laravel 6+ users, I agreed with the top 2 answers its all depends on laravel versions, For the latest versions users id column uses big integer. So referencing the users id from current migration you need to use unsignedBigInteger as a reference key. Bellow is a migration example for laravel 6.5.*, Whenever we assign foreign key Keep in mind of your current laravel version

Schema::create('galleries', function (Blueprint $table) {
        $table->bigIncrements('id');
        ==>$table->unsignedBigInteger('user_id');
        $table->string('title');
        $table->string('description');
        $table->timestamps();
        ==>$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });


来源:https://stackoverflow.com/questions/47728909/laravel-migration-errno-150-foreign-key-constraint-is-incorrectly-formed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!