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

后端 未结 22 713
有刺的猬
有刺的猬 2020-11-30 07:21

When migrating my DB, this error appears. Below is my code followed by the error that I am getting when trying to run the migration.

Code



        
相关标签:
22条回答
  • 2020-11-30 07:59

    Please add ->nullable() on your field and make sure that all the fields you're referring to really exist.

    0 讨论(0)
  • 2020-11-30 08:02

    When creating a new table in Laravel. A migration will be generated like:

    $table->bigIncrements('id');
    

    Instead of (in older Laravel versions):

    $table->increments('id');
    

    When using bigIncrements the foreign key expects a bigInteger instead of an integer. So your code will look like this:

    public function up()
        {
            Schema::create('meals', function (Blueprint $table) {
                $table->increments('id');
                $table->unsignedBigInteger('user_id'); //changed this line
                $table->unsignedBigInteger('category_id'); //changed this line
                $table->string('title');
                $table->string('body');
                $table->string('meal_av');
                $table->timestamps();
    
                $table->foreign('user_id')
                    ->references('id')
                    ->on('users')
                    ->onDelete('cascade');
    
                $table->foreign('category_id')
                    ->references('id')
                    ->on('categories')
                    ->onDelete('cascade');
            });
        }  
    

    You could also use increments instead of bigIncrements like Kiko Sejio said.

    The difference between Integer and BigInteger is the size:

    • int => 32-bit
    • bigint => 64-bit
    0 讨论(0)
  • 2020-11-30 08:04

    I got the same message for data type miss-matched problem.

    I used bigIncrements() for 'id' and when I used it as foreign key (used bigInteger()) I got the error.

    I have found the solution, bigIncrements() returns unsignedBigInteger. So need to use unsignedBigInteger() instead of bigInteger() in foreign key

    Sharing this because it might help others

    0 讨论(0)
  • 2020-11-30 08:08

    Laravel 6: Update on 17 Jan 2020

    $table->bigInteger( 'category_id' )->unsigned();
    

    This worked well for me

    0 讨论(0)
提交回复
热议问题