Home » Php » php – Laravel (MySQL) migration FK works when it's onDelete('CASCADE') but throws an error for onDelete('SET DEFAULT')

php – Laravel (MySQL) migration FK works when it's onDelete('CASCADE') but throws an error for onDelete('SET DEFAULT')

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a migration in Laravel with a foreign key,

It works fine when I set onDelete('CASCADE') but throws an error for onDelete('SET DEFAULT')

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table users add constraint users_theme_id_foreign foreign key (theme_id) references themes (id) on delete SET DEFAULT on update cascade)

Themes table (this runs before the users table):

Schema::create('themes', function (Blueprint $table) {
    $table->smallIncrements('id');
    $table->string('color')->nullable();
});

// Inserting default theme
DB::table('themes')->insert([
    'id'    => 1,
    'name'  => 'Something'
]);

Users table (only FK and theme_id column):

Schema::create('users', function (Blueprint $table) {
    ...
    $table->unsignedSmallInteger('theme_id')->default(1);
    ...
    $table->foreign('theme_id')->references('id')->on('themes')->onDelete('SET DEFAULT')->onUpdate('SET DEFAULT');
});

Update:

As I said the users migration above fails, but weirdly as soon as I replace the Foreign Key to CASCADE it works just fine!

$table->foreign('theme_id')->references('id')->on('themes')->onDelete('CASCADE')->onUpdate('CASCADE');

More Info:

  • Both tables are InnoDB and have the same Encoding and Collation.
  • Laravel 6.15.0
  • PHP v7.4.1
  • MySQL v5.7.26
How to&Answers: