Ad

Laravel Migration: Errno: 150 "Foreign Key Constraint Is Incorrectly Formed"

- 1 answer

I receive the error

SQLSTATE[HY000]: General error: 1005 Can't create tableposys.#sql-2b94_d2(errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter tablepurchase_ordersadd constraint purchase_orders_status_id_foreignforeign key (status_id) referencesstatuses(id))

When running my migration.

Here are my migrations:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStaffTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('staff', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->string('position')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('staff');
    }
}

And

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePurchaseOrdersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('purchase_orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->float('total_price_ex_vat', 12, 2);
            $table->float('total_price_inc_vat', 12, 2);
            $table->string('deliver_to'); 
            $table->unsignedBigInteger('staff_id'); // Foreign key
            $table->foreign('staff_id')->references('id')->on('staff');
            $table->unsignedBigInteger('supplier_id'); // Foreign key
            $table->foreign('supplier_id')->references('id')->on('suppliers');
            $table->unsignedBigInteger('status_id'); // Foreign key
            $table->foreign('status_id')->references('id')->on('statuses');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('purchase_orders');
    }
}
Ad

Answer

To avoid error 150, pick one:

  • Rearrange the order of CREATE TABLEs
  • DISABLE FKs, do the creates, enable them.
  • Don't ADD the FKs until all the CREATEs have been done.
Ad
source: stackoverflow.com
Ad