コード例 #1
0
 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);
             }
             if (!empty($remove_role_menu_ids)) {
                 $remove_role_menu_id_str = implode(',', $remove_role_menu_ids);
                 $table = AdminRoleMenu::tableName();
                 $sql = "delete from {$table} where menu_id in ({$remove_role_menu_id_str} ) and role_id = :role_id ";
                 $data = ['role_id' => $roleId];
                 CDB::deleteBySql($sql, $data);
             }
             $innerTransaction->commit();
         } catch (Exception $e) {
             $innerTransaction->rollBack();
         }
     }
 }