public function saveMenuAndRole() { if ($this->_one[$this->_paramKey]) { $roleId = $this->_one[$this->_paramKey]; $this->_one->save(); } else { $this->_one->save(); $roleId = Yii::$app->db->getLastInsertID(); } $menu = CRequest::param("menu"); $select_menus = isset($menu['select_menus']) ? $menu['select_menus'] : ''; # 如果存在role_id 和选择的菜单 if ($roleId && $select_menus) { # 得到当前选择的menu_id和相应的所有上级menu_id $select_menu_ids = $this->getAllParentMenuIds($select_menus); $select_menu_ids = array_unique($select_menu_ids); # AdminRole中role_id 对应的所有 menu_id $role_menu_ids = $this->getDbRoleMenuIds($roleId); # 需要插入的role_id - menu_id 数组差集 $add_role_menu_ids = array_diff($select_menu_ids, $role_menu_ids); # 需要删除的role_id - menu_id 数组差集 $remove_role_menu_ids = array_diff($role_menu_ids, $select_menu_ids); # 事务 插入 和 删除 role_menu 表中,当前role_id 对应的menu_id $table = 'admin_role_menu'; $columnsArr = ['menu_id', 'role_id', 'created_at', 'updated_at']; $valueArr = []; $now_date = date("Y-m-d H:i:s"); if (!empty($add_role_menu_ids)) { foreach ($add_role_menu_ids as $menu_id) { $valueArr[] = [$menu_id, $roleId, $now_date, $now_date]; } } $innerTransaction = Yii::$app->db->beginTransaction(); try { if (!empty($add_role_menu_ids)) { \fec\helpers\CDB::batchInsert($table, $columnsArr, $valueArr); } AdminRoleMenu::deleteAll(['in', 'menu_id', $remove_role_menu_ids]); $innerTransaction->commit(); } catch (Exception $e) { $innerTransaction->rollBack(); } } }
public function saveUserRole($user_id) { $role = CRequest::param("role"); $role_ids = []; if (!empty($role)) { //var_dump($role); $innerTransaction = Yii::$app->db->beginTransaction(); try { foreach ($role as $k => $role_id) { $one = AdminUserRole::findOne(['role_id' => $role_id, 'user_id' => $user_id]); $role_ids[] = $role_id; if (!$one['id']) { $one = new AdminUserRole(); $one->role_id = $role_id; $one->user_id = $user_id; $one->save(); } } $table = AdminUserRole::tableName(); if (!empty($role_ids)) { $role_str = implode(",", $role_ids); $sql = "delete from {$table} where user_id = {$user_id} and role_id not in ({$role_str})"; } else { $innerTransaction->rollBack(); echo json_encode(["statusCode" => "300", "message" => "您至少要勾选一个用户权限组"]); exit; } CDB::deleteBySql($sql); $innerTransaction->commit(); } catch (Exception $e) { $innerTransaction->rollBack(); echo json_encode(["statusCode" => "300", "message" => 'Save User Role Fail !']); exit; } } else { echo json_encode(["statusCode" => "300", "message" => "您至少要勾选一个用户权限组"]); exit; } }