Laravel foreign key onDelete('cascade') no

2019-02-13 22:20发布

I have a many-to-many relationship between User & Role, with a role_user table. My migrations are setup as so (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');
    });
}

So as per the docs, I set my foreign keys to unsigned.

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

What am I doing wrong?

  • MySQL + InnoDB

EDIT: Grabbing the model and applying ->delete(); also has the same effect.

2条回答
姐就是有狂的资本
2楼-- · 2019-02-13 23:04

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

$table->engine = 'InnoDB';

I have filed a bug under: https://github.com/laravel/framework/issues/8730

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-13 23:05

Check mysql config. my.ini may still have default-storage-engine=MYISAM. Set to default-storage-engine=InnoDB and you should avoid the trouble of adding this fix to each migration.

查看更多
登录 后发表回答