Laravel foreign key onDelete ("cascade") does not work

I have a many-to-many relationship between the user and the role with the role_user table. My migrations are configured as follows (simplified):

users table:

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

roles table:

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

role_user table:

 public function up() { Schema::create('role_user', function(Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->integer('role_id')->unsigned(); $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade'); }); } 

According to the docs, I set the foreign keys to unsigned.

Now I add a couple of users and apply several roles - everything works fine. However, when I delete the user ( User::destroy(2) ), the rows for that user in the role_user table role_user not deleted, which causes redundant rows.

What am I doing wrong?

  • MySQL + InnoDB

EDIT: model capture and application ->delete(); also have the same effect.

+6
source share
2 answers

Try setting when trying to create this table. This fix worked for me.

 $table->engine = 'InnoDB'; 

I filed an error: https://github.com/laravel/framework/issues/8730

+11
source

Check mysql configuration. My.ini can still have a default storage file - MYISAM. Set default-storage-engine = InnoDB, and you should avoid the trouble of adding this hotfix to each migration.

+1
source

Source: https://habr.com/ru/post/972671/


All Articles