where(function ($q) use ($params) { $q->where('name', 'like', '%' . $params['keyword'] . '%') ->orWhere('code', 'like', '%' . $params['keyword'] . '%'); }); } // 状态筛选 if (isset($params['status'])) { $query->where('status', $params['status']); } // 角色类型筛选 if (isset($params['type'])) { $query->where('type', $params['type']); } // 数据范围筛选 if (isset($params['data_scope'])) { $query->where('data_scope', $params['data_scope']); } // 排序 $query->orderBy('sort', 'asc') ->orderBy('id', 'desc'); return $query->paginate($params['page_size'] ?? 15); } /** * 获取简单列表(用于下拉选择等) */ public function getSimpleList(): array { return SystemRole::select('id', 'name', 'code') ->where('status', 0) ->orderBy('sort', 'asc') ->get() ->toArray(); } /** * 创建前验证 */ protected function beforeCreate(array &$data): void { // 如果没有设置排序,自动设置为最大值+1 if (!isset($data['sort'])) { $maxSort = SystemRole::max('sort') ?? 0; $data['sort'] = $maxSort + 1; } // 默认状态为正常 if (!isset($data['status'])) { $data['status'] = 0; } // 默认数据范围为本部门数据权限 if (!isset($data['data_scope'])) { $data['data_scope'] = 3; } } /** * 更新前验证 */ protected function beforeUpdate(array &$data, $model): void { // 处理数据范围部门IDs if (isset($data['data_scope_dept_ids']) && is_array($data['data_scope_dept_ids'])) { $data['data_scope_dept_ids'] = implode(',', $data['data_scope_dept_ids']); } } /** * 检查角色编码是否存在 */ public function checkCodeExists(string $code, ?int $excludeId = null): bool { $query = SystemRole::where('code', $code); if ($excludeId) { $query->where('id', '!=', $excludeId); } return $query->exists(); } /** * 批量更新状态 */ public function batchUpdateStatus(array $ids, int $status): bool { return SystemRole::whereIn('id', $ids)->update(['status' => $status]) > 0; } }