Laravel 外键 onDelete('cascade') 不起作用 [英] Laravel foreign key onDelete('cascade') not working

查看:19
本文介绍了Laravel 外键 onDelete('cascade') 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 User & 之间有一个多对多的关系角色,带有一个 role_user 表.我的迁移是这样设置的(简化):

I have a many-to-many relationship between User & Role, with a role_user table. My migrations are setup as so (simplified):

users 表:

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

roles 表:

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

role_user 表:

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.

现在,我添加了几个用户,并附加了一些角色 - 一切正常.但是,当我删除用户 (User::destroy(2)) 时,role_user 表中该用户的行不会被删除,这会导致冗余行.

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.

我做错了什么?

  • MySQL + InnoDB

抓取模型并应用 ->delete(); 也有同样的效果.

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

推荐答案

尝试创建此表时尝试设置.此修复程序对我有用.

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

$table->engine = 'InnoDB';

我在以下位置提交了一个错误:https://github.com/laravel/framework/issues/8730

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

这篇关于Laravel 外键 onDelete('cascade') 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆