如何在 Laravel 的级联上使用删除?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38350036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use delete on cascade in Laravel?
提问by moh
I have a 'Roles' table:
我有一个“角色”表:
$table->increments('id');
$table->string('name')->unique();
$table->text('description')->nullable();
and a 'Roles_Users' table:
和一个“Roles_Users”表:
$table->increments('id');
$table->integer('role_id')->unsigned()->index()->foreign()->references("id")->on("roles")->onDelete("cascade");
$table->integer('user_id')->unsigned()->index()->foreign()->references("id")->on("users")->onDelete("cascade");
When I run such a line:
当我运行这样一行时:
Role::where('name','someString')->delete();
only the related row in the Roles table is deleted, and related rows in the Roles_Users table aren't. what is the solution?
只有 Roles 表中的相关行被删除,而 Roles_Users 表中的相关行不被删除。解决办法是什么?
回答by Asher
I recommend that you create a "foreign key" constraint for this case (as others mentioned). Also because this is a many-to-many relationship, you can use detach()
method on your Eloquent model (if you sat the relations correctly in your user
and role
models)
我建议您为这种情况创建一个“外键”约束(正如其他人提到的)。也因为这是一个多对多的关系,你可以detach()
在你的 Eloquent 模型上使用方法(如果你在你的user
和role
模型中正确地放置了关系)
$user = App\User::find(1);
// Detach all roles from the user...
$user->roles()->detach();
You can relate to the documentation for more details.
您可以参考文档了解更多详情。
回答by Kapil Garg
Try to apply $table->index(['role_id', 'user_id'])
and foreign keys after creating columns. So Your code will look like
$table->index(['role_id', 'user_id'])
创建列后尝试应用和外键。所以你的代码看起来像
Schema::table('role_users', function($table){
$table->increments('id') ;
$table->integer('role_id')->unsigned() ;
$table->integer('user_id')->unsigned()
});
Schema::table('role_users', function($table){
$table->index(['role_id', 'user_id'])
}) ;
Schema::table('role_users', function($table){
$table->foreign()->references("id")->on("roles")->onDelete("cascade");
$table->foreign()->references("id")->on("users")->onDelete("cascade");
}) ;