Laravel外键onDelete('cascade')不起作用 [英] Laravel foreign key onDelete('cascade') not working
问题描述
我与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屋!