On this page
给角色配置权限
控制器 app/controller/admin/Role.php
php
// 给角色授予权限
public function setRules(){
$param = request()->param();
$rules = getValByKey('rule_ids',$param,[]);
return showSuccess(request()->Model->setRules($rules));
}
验证器 app/validate/admin/Role.php
php
// 验证规则
protected $rule = [
...
'id'=>'require|integer|>:0|isExist:role',
'rule_ids'=>'array'
...
];
protected $scene = [
...
'setRules'=>['id','rule_ids'],
];
模型 app/model/Role.php
php
// 给角色授予权限
public function setRules($ruleId){
// 获取当前角色的所有权限Id
$Ids = \app\model\RoleRule::where('role_id',$this->id)->column('rule_id');
// 需要添加的
$addIds = array_diff($ruleId,$Ids);
// 需要删除的
$delIds = array_diff($Ids,$ruleId);
if (count($addIds)>0) {
$RoleRule = new \app\model\RoleRule();
$addData = [];
foreach ($addIds as $value) {
$addData[] = [
'rule_id'=>$value,
'role_id'=>$this->id
];
}
$RoleRule->saveAll($addData);
}
if (count($delIds) > 0) {
\app\model\RoleRule::where([
['rule_id','in',$delIds],
['role_id','=',$this->id]
])->delete();
}
return true;
}
路由 router/admin.php
php
// 设置角色权限
Route::post('role/set_rules','admin.Role/setRules');