Search code examples
phplaravelmigrationdatabase-migrationlaravel-8

Laravel 8 Migration "General error: 1215 Cannot add foreign key constraint"


I'm trying to create a migration on Laravel 8, Here's my table

class CreateProductVariationOrderTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('product_variation_order', function (Blueprint $table) {
            $table->integer('order_id')->unsigned()->index();
            $table->integer('product_variation_id')->unsigned()->index();
            $table->integer('quantity')->unsigned();
            $table->timestamps();

            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
            $table->foreign('product_variation_id')->references('id')->on('product_variations')->onDelete('cascade');
        });
    }
    public function down()
    {
        Schema::dropIfExists('product_variation_order');
    }
}

And When I run php artisan migrate I get this chunk of error : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table product_variation_orderadd constraintproduct_variation_order_order_id_foreign foreign key (order_id) references orders (id) on delete cascade)

⚠️ EDIT: Here's my product_variation migration file.

class CreateProductVariationsTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('product_variations', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('product_id')->unsigned()->index();
            $table->string('name');
            $table->integer('price')->nullable();
            $table->integer('order')->nullable();
            $table->timestamps();

            $table->foreign('product_id')->references('id')->on('products');
        });
    }

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

Solution

  • The foreign key has to be the same type as the reference key.

    In your orders table, you define id as bigIncrements() which is unsigned big integer.

    In your product_variation_order table, you define order_id as unsigned integer.

    So the two keys do not match. Generally you should use big integer because it allows your database to grow larger and space difference between integer and big integer isn't significant.

    So change order_id as unsigned big integer.

    $table->unsignedBigInteger('order_id')->nullable();
    

    Also for consistency, all keys should be bigIncrements() or unsignedBigInteger(), this will save you headache in the future.