- 关联写入
- 多对多的新增:比如,给用户增加一个角色权限,具体如下;
//得到要添加权限的用户
$user = User::find(26);
//得到权限的id,比如超级管理员
$roleId = 3;
//给辉夜设置成超级管理员
$user->role()->attach($roleId);
b. 如果你想给中间的表附加details 字段的数据,可以使用第二参数
$user->role()->attach($roleId, [‘details’=>’嘎’]);
c. 如果想移出某个用户的角色权限,可以使用detach()方法;
//删除一个角色权限
$user->role()->detach($roleId);
PS:如果不指定中间表id,那么就移出这个用户的所有权限角色;
d. 也支持批量处理,直接用数组传递参数即可:
//这里传递的是角色权限表的ID
$user->role()->attach([1, 2, 3]); // 1 => [‘details’=>’xxx’]
//删除指定的user_id
$user->role()->detach([1, 2, 3]);
e. 使用sync()方法,可以新增角色权限,且可以判断已经存在而不再新增:
//同步关联,已存在就不再新增
$user->role()->sync([1, 2, 3]); // 1 => [‘details’=>’xxx’]
f. 使用udpateExitstingPivot()可更新指定roleId的额外字段:
//更新中间表的额外字段
$user->role()->updateExistingPivot($roleId, [‘details’=>’喀’]);
PS: 直接使用update()是更新所有;$user->role()->update([‘details’=>’啦’]);
PS: 通过查看源代码或IDE代码提示的方法,有更多的操作;可自行阅读扩展;