laravel - 多对多关系同步删除所有选定的选项

标签 laravel many-to-many

我有一个多对多关系的角色和权限表,以及数据透视表 permission_role .我在尝试更新角色权限时遇到的这个问题。
例如:创建管理员角色时:我添加了权限:view_users到它。现在尝试更新它时,给它额外的权限 create_team .
编码:

$roleUpdate = Role::where('id', $role->id)->update([
    'name' => $request->input('name'),
    'updated_at' => Carbon::now()
]);

$permissions = $request->input('permission');

//dd($permissions);

foreach ($permissions as $permission) {
    $role->permissions()->sync($permission, true);
}

if ($roleUpdate) {
    Alert::toast('Role updated successfully', 'success');
    return redirect()
        ->route('roles.index', ['role' => $role->id])
        ->with('success', 'Role Updated Successfully');
}

//redirect
return back()->withInput();
当我dd()在查看通过哪些选项的权限后,我得到了预期和正确的结果
array:2 [▼
  0 => "3"
  1 => "4"
]
但是,当数据保存到数据库中时,只会存储新值并删除旧值。我了解该问题可能是由于在此行上将 detach 设置为 true 引起的:
$role->permissions()->sync($permission,true); 
但是,如果我将其设置为 false,那么当我通过删除其中一项权限来更新角色的权限时,它将不起作用。它不会分离。根据下面链接中的文档中给出的解释,它似乎不起作用。不知道我错过了什么
Laravel Docs

最佳答案

问题是您正在使用 foreach:

array:2 [▼
  0 => "3"
  1 => "4"
]

foreach ($permissions as $permission) {
    $role->permissions()->sync($permission, true);
}
在第一个循环中,您删除角色的所有权限,但 ID 为 3 的权限除外。 ,在第二个循环中,您再次从角色中删除所有权限,但 ID 为 4 的权限除外。 ,这意味着您已经删除了之前设置的 ID 为 3 的权限.
删除 foreach 并传递整个数组应该可以工作:
// no need to pass 'true' as the second argument as it is the default value
$role->permissions()->sync($request->input('permission'));
来自 docs :

You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:

$user->roles()->sync([1, 2, 3]);

关于laravel - 多对多关系同步删除所有选定的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62930291/

相关文章:

php - Laravel 数据库插入错误 : Allowed Memory Size Exhausted

laravel - 如何使用 laravel eloquent 设置开始和结束偏移量来检索 block 中的数据?

java - Hibernate单向ManyToMany更新目标构成关系

security - 使用 Backbone.js、Require.js 和 Laravel 的 SPA 安全性

php - Laravel迁移创建具有多个主键的表

javascript - 单个文件组件的Vue i18n转换

python - 如何从 SqlAlchemy 中的多对多集合中删除所有项目?

c# - Xamarin SQLite - 多对多关系

django - django admin 中的通用多对多关系

java - Hibernate 多对多级联删除