0

I'm having problems with running my migration. I have a mysql database with some tables. The specific table is product_blender. Some fields in the table are like this:

  • id (PK)
  • area_id (FK)
  • inhabitants (varchar)
  • heating_type_id (FK)
  • ...

Now I would like to create another table called installateur_types. The table needs to contain a PK and a varchar field. I would also like to create a FK in product_blender table to the id of my newly created tabel.

This is what I've done:

Created migration to create a table:

public function up()
{
    Schema::create('installateur_types', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('type');
    });
}

public function down()
{
    Schema::drop('installateur_types');
}

Run the migration, this was successful. Table was created with correct fields.

Then I've created the migration to add a FK field to the product_blender table.

public function up()
{
    Schema::table('product_blenders', function ($table) {
        $table->integer('installateurtype_id')->unsigned();
        $table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade');
    });
}

public function down()
{
    //
}

When I now run the migration I get the following error: enter image description here

What am I doing wrong?

1
  • Does product_blenders table existed previously? Commented Oct 21, 2015 at 10:27

1 Answer 1

5

If your products_blender table is not empty, then when you add a new column which is not null (which is the default for eloquent), it will be assuming some default value on its own. This value may not be available in the table this new column is referring to, causing the foreign key constraint to fail.

One of the way to get around this is to give a default value to the new column or just make it nullable.

$table->integer('installateurtype_id')->unsigned()->nullable();
$table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade');

There is one other solution, which turns off this checks, which can be done using DB::statement('SET FOREIGN_KEY_CHECKS=0;'). Then again turn that one for future with DB::statement('SET FOREIGN_KEY_CHECKS=1;'). In you code you can do something like

DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$table->integer('installateurtype_id')->unsigned();
$table->foreign('installateurtype_id')->references('id')->on('installateur_types')->onDelete('cascade');
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.