# 6.4 部门管理 :::tip 概述 部门管理维护组织架构数据,支持树形结构,是数据权限(按部门过滤)的基础。继承 BaseTenantLogic 实现租户隔离。 ::: ## 模块特点 | 特性 | 说明 | |------|------| | 基类 | BaseTenantLogic(租户隔离) | | 树形结构 | treeParentField='parent_id' | | 唯一校验 | name 全局唯一 | | 删除校验 | beforeDelete 检查是否存在子部门 | | 数据权限 | 被 UserLogic 的 dataScopeDeptField='dept_id' 引用 | ## 数据库表结构 ```sql CREATE TABLE `think_dept` ( `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID', `name` varchar(150) NOT NULL COMMENT '部门名称', `type` int DEFAULT 0 COMMENT '部门类型:1-公司 2-子公司 3-部门 4-小组', `parent_id` int DEFAULT 0 COMMENT '上级部门ID', `sort` int DEFAULT 0 COMMENT '部门排序', `note` varchar(255) DEFAULT NULL COMMENT '备注', `create_user` varchar(50) DEFAULT NULL COMMENT '创建人', `create_time` datetime DEFAULT (now()) COMMENT '创建时间', `update_user` varchar(50) DEFAULT NULL COMMENT '更新人', `update_time` datetime DEFAULT (now()) COMMENT '更新时间', `is_delete` int DEFAULT 0 COMMENT '删除标识:0-正常 1-已删除', PRIMARY KEY (`id`) ) COMMENT = '部门表'; ``` ## API 接口 | 方法 | 路径 | 权限码 | 说明 | |------|------|--------|------| | GET | `/api/dept/list` | sys:dept:page | 树形列表 | | GET | `/api/dept/detail/:id` | sys:dept:detail | 详情 | | POST | `/api/dept/add` | sys:dept:add | 新增 | | PUT | `/api/dept/update` | sys:dept:update | 修改 | | DELETE | `/api/dept/delete/:id` | sys:dept:delete | 删除 | ## 核心代码 ### Logic 配置 ```php // app/logic/DeptLogic.php class DeptLogic extends BaseTenantLogic { /** * 关联的模型类 * * @var string */ protected string $modelClass = Dept::class; /** * LIKE 模糊匹配字段 * * @var array */ protected array $pageLikeFields = ['name']; /** * 精确匹配字段 * * @var array */ protected array $pageEqFields = ['type']; /** * 默认排序规则 * * @var array */ protected array $pageOrderBy = [ ['field' => 'tenant_id', 'type' => 'asc'], ['field' => 'sort', 'type' => 'asc'], ]; /** * 唯一性校验字段 * * @var array */ protected array $uniqueFields = ['name']; /** * 删除前处理:检查是否存在子部门 * * @param int $id 待删除的部门 ID * @return void * @throws \Exception 当存在子部门时抛出 */ protected function beforeDelete(int $id): void { $childCount = Dept::where('parent_id', $id)->count(); if ($childCount > 0) { throw new \Exception('该部门下存在子部门,不可删除'); } } } ``` :::tip 树形接口 部门使用 `_list()` 而非 `_index()`,返回全量数据后由前端或 Logic 构建树形结构。 ::: ### Controller 示例 ```php // app/controller/DeptController.php class DeptController extends BaseController { protected DeptLogic $logic; protected function initialize(): void { $this->logic = new DeptLogic(); } #[Log('部门管理-查询树形列表', Log::TYPE_QUERY)] #[Permission('sys:dept:page', '部门列表')] public function list(): Json { return parent::_list($this->logic); } #[Log('部门管理-新增记录', Log::TYPE_ADD, '新增部门:{name}')] #[Permission('sys:dept:add', '添加部门')] public function add(): Json { return parent::_add($this->logic, $this->getJsonBody()); } // ... 其他 CRUD 方法 } ```