# 关系映射说明 **本文档引用的文件** - [models.py](file://backend/app/models/models.py) - [finance.py](file://backend/app/models/finance.py) - [database.py](file://backend/app/core/database.py) - [config.py](file://backend/app/core/config.py) - [001_initial.py](file://backend/alembic/versions/001_initial.py) - [002_template.py](file://backend/alembic/versions/002_template.py) - [staff_service.py](file://backend/app/services/staff_service.py) - [assessment_service.py](file://backend/app/services/assessment_service.py) - [department_service.py](file://backend/app/services/department_service.py) - [departments.py](file://backend/app/api/v1/departments.py) - [assessments.py](file://backend/app/api/v1/assessments.py) - [database.md](file://docs/database.md) - [backend.md](file://docs/backend.md) ## 目录 1. [简介](#简介) 2. [项目结构](#项目结构) 3. [核心组件](#核心组件) 4. [架构概览](#架构概览) 5. [详细组件分析](#详细组件分析) 6. [依赖分析](#依赖分析) 7. [性能考虑](#性能考虑) 8. [故障排除指南](#故障排除指南) 9. [结论](#结论) ## 简介 本文件详细说明医院绩效管理系统的数据模型关系映射设计。系统采用SQLAlchemy ORM实现,涵盖科室层级结构、员工与科室关系、考核记录与明细关系等复杂业务场景。重点解释一对一、一对多、多对多关系的实现方式,包括外键约束、级联删除、反向关系和懒加载机制。 ## 项目结构 系统采用分层架构,核心模型位于`backend/app/models/`目录,数据库配置在`backend/app/core/`目录,服务层在`backend/app/services/`目录,API路由在`backend/app/api/v1/`目录。 ```mermaid graph TB subgraph "数据模型层" A[models.py
核心业务模型] B[finance.py
财务模型] C[__init__.py
模型导出] end subgraph "核心配置层" D[database.py
数据库连接] E[config.py
系统配置] end subgraph "服务层" F[staff_service.py
员工服务] G[assessment_service.py
考核服务] H[department_service.py
科室服务] end subgraph "API层" I[departments.py
科室API] J[assessments.py
考核API] end A --> D B --> D F --> A G --> A H --> A I --> H J --> G ``` **图表来源** - [models.py](file://backend/app/models/models.py#L1-L438) - [database.py](file://backend/app/core/database.py#L1-L39) - [staff_service.py](file://backend/app/services/staff_service.py#L1-L112) - [assessment_service.py](file://backend/app/services/assessment_service.py#L1-L263) **章节来源** - [models.py](file://backend/app/models/models.py#L1-L438) - [database.py](file://backend/app/core/database.py#L1-L39) ## 核心组件 系统包含以下核心数据模型: ### 基础模型 - **Base**: SQLAlchemy DeclarativeBase基类 - **异步数据库引擎**: 基于asyncpg的异步连接 - **会话管理**: 自动事务管理和连接池配置 ### 业务模型 - **Department**: 科室信息,支持自关联 - **Staff**: 员工信息,一对多关联科室 - **Assessment**: 考核记录,一对多关联员工 - **AssessmentDetail**: 考核明细,多对多中间表 - **Indicator**: 考核指标,支持BSC维度 - **SalaryRecord**: 工资核算记录 - **User**: 系统用户,关联员工 - **PerformancePlan**: 绩效计划,支持层级结构 - **PlanKpiRelation**: 计划指标关联 - **IndicatorTemplate**: 指标模板 - **TemplateIndicator**: 模板指标关联 - **DepartmentFinance**: 科室财务记录 **章节来源** - [models.py](file://backend/app/models/models.py#L62-L438) - [finance.py](file://backend/app/models/finance.py#L45-L79) ## 架构概览 系统采用经典的三层架构模式,通过ORM模型实现业务逻辑与数据持久化的分离。 ```mermaid erDiagram DEPARTMENTS ||--o{ STAFF : "一对多" STAFF ||--o{ ASSESSMENTS : "一对多" ASSESSMENTS ||--o{ ASSESSMENT_DETAILS : "一对多" INDICATORS ||--o{ ASSESSMENT_DETAILS : "一对多" STAFF ||--o{ SALARY_RECORDS : "一对多" DEPARTMENTS ||--o{ DEPARTMENT_FINANCES : "一对多" USERS ||--|| STAFF : "一对一" PERFORMANCE_PLANS ||--o{ PLAN_KPI_RELATIONS : "一对多" INDICATORS ||--o{ PLAN_KPI_RELATIONS : "一对多" INDICATOR_TEMPLATES ||--o{ TEMPLATE_INDICATORS : "一对多" INDICATORS ||--o{ TEMPLATE_INDICATORS : "一对多" DEPARTMENTS { int id PK string name string code UK enum dept_type int parent_id FK int level int sort_order boolean is_active } STAFF { int id PK string employee_id UK string name int department_id FK string position string title float base_salary float performance_ratio enum status } ASSESSMENTS { int id PK int staff_id FK int period_year int period_month enum status float total_score float weighted_score } ASSESSMENT_DETAILS { int id PK int assessment_id FK int indicator_id FK float actual_value float score } INDICATORS { int id PK string code UK enum indicator_type enum bs_dimension float weight float max_score } ``` **图表来源** - [models.py](file://backend/app/models/models.py#L62-L438) - [001_initial.py](file://backend/alembic/versions/001_initial.py#L22-L183) ## 详细组件分析 ### 科室层级结构关系 科室模型实现了完整的自关联关系,支持多层级的组织架构。 ```mermaid classDiagram class Department { +int id +string name +string code +DeptType dept_type +int parent_id +int level +int sort_order +boolean is_active +Department parent +Department[] children +Staff[] staff } Department "1" <-- "0..*" Department : "parent" Department "1" --> "0..*" Department : "children" Department "1" --> "0..*" Staff : "staff" ``` **实现特点**: - 使用`remote_side`参数解决自关联的歧义性 - 通过`backref="children"`实现反向关系 - 支持多层级嵌套结构 - 通过`level`字段维护层级深度 **章节来源** - [models.py](file://backend/app/models/models.py#L62-L85) ### 员工与科室关系 员工与科室之间是一对多的关系,通过外键约束保证数据完整性。 ```mermaid sequenceDiagram participant Client as "客户端" participant API as "部门API" participant Service as "DepartmentService" participant DB as "数据库" Client->>API : GET /api/v1/departments/tree API->>Service : get_tree(dept_type) Service->>DB : SELECT * FROM departments ORDER BY sort_order, id DB-->>Service : 部门列表 Service->>Service : 构建树形结构 Service-->>API : 树形结构数据 API-->>Client : 返回科室树 ``` **图表来源** - [departments.py](file://backend/app/api/v1/departments.py#L43-L51) - [department_service.py](file://backend/app/services/department_service.py#L113-L126) **实现特点**: - 使用`selectinload`优化N+1查询问题 - 支持按科室类型过滤 - 手动构建树形结构避免懒加载问题 **章节来源** - [models.py](file://backend/app/models/models.py#L88-L114) - [department_service.py](file://backend/app/services/department_service.py#L113-L126) ### 考核记录与明细关系 考核系统采用主从结构,支持复杂的多对多关系。 ```mermaid classDiagram class Assessment { +int id +int staff_id +int period_year +int period_month +AssessmentStatus status +float total_score +float weighted_score +AssessmentDetail[] details +Staff staff } class AssessmentDetail { +int id +int assessment_id +int indicator_id +float actual_value +float score +Indicator indicator +Assessment assessment } class Indicator { +int id +string code +IndicatorType indicator_type +float weight +AssessmentDetail[] assessment_details } Assessment "1" --> "0..*" AssessmentDetail : "details" AssessmentDetail "1" --> "1" Staff : "staff" AssessmentDetail "1" --> "1" Indicator : "indicator" Indicator "1" --> "0..*" AssessmentDetail : "assessment_details" ``` **实现特点**: - 使用`cascade="all, delete-orphan"`实现级联删除 - 通过`foreign_keys`参数区分多重外键关系 - 支持复杂的统计计算(总分、加权得分) **章节来源** - [models.py](file://backend/app/models/models.py#L149-L202) - [assessment_service.py](file://backend/app/services/assessment_service.py#L71-L108) ### 财务核算关系 财务模块与科室建立了清晰的一对多关系。 ```mermaid flowchart TD Start([财务记录创建]) --> Validate["验证科室存在性"] Validate --> CreateRecord["创建财务记录"] CreateRecord --> Save["保存到数据库"] Save --> LoadDept["加载科室信息"] LoadDept --> Return["返回完整记录"] Validate --> |验证失败| Error["返回错误"] Error --> End([结束]) Return --> End ``` **图表来源** - [finance.py](file://backend/app/models/finance.py#L45-L79) **实现特点**: - 使用`backref="finances"`简化反向访问 - 通过枚举类型管理财务类别 - 实现金额正数约束 **章节来源** - [finance.py](file://backend/app/models/finance.py#L45-L79) ### 指标模板关系 指标模板系统支持复杂的多对多关系。 ```mermaid erDiagram INDICATOR_TEMPLATES ||--o{ TEMPLATE_INDICATORS : "一对多" INDICATORS ||--o{ TEMPLATE_INDICATORS : "一对多" INDICATOR_TEMPLATES { int id PK string template_code UK enum template_type boolean is_active } TEMPLATE_INDICATORS { int id PK int template_id FK int indicator_id FK float weight int sort_order } INDICATORS { int id PK string code UK enum indicator_type enum bs_dimension float weight } ``` **实现特点**: - 使用复合唯一索引防止重复关联 - 支持模板级别的权重管理 - 提供排序字段支持显示顺序 **章节来源** - [models.py](file://backend/app/models/models.py#L387-L438) ## 依赖分析 系统采用模块化设计,各层之间依赖关系清晰。 ```mermaid graph TB subgraph "外部依赖" A[SQLAlchemy] B[FastAPI] C[Alembic] D[asyncpg] end subgraph "核心模块" E[database.py] F[models.py] G[finance.py] end subgraph "业务模块" H[staff_service.py] I[assessment_service.py] J[department_service.py] end subgraph "接口模块" K[departments.py] L[assessments.py] end A --> E B --> K B --> L C --> F D --> E E --> F E --> G F --> H F --> I F --> J H --> K I --> L ``` **图表来源** - [database.py](file://backend/app/core/database.py#L1-L39) - [models.py](file://backend/app/models/models.py#L1-L13) - [staff_service.py](file://backend/app/services/staff_service.py#L1-L11) - [assessment_service.py](file://backend/app/services/assessment_service.py#L1-L11) **依赖特性**: - 异步数据库连接支持高并发 - 模块化导入避免循环依赖 - 明确的层次边界确保代码可维护性 **章节来源** - [config.py](file://backend/app/core/config.py#L18-L26) - [database.py](file://backend/app/core/database.py#L1-L39) ## 性能考虑 ### 查询优化策略 1. **懒加载与急加载选择** - 使用`selectinload`避免N+1查询问题 - 在API层根据需要选择性加载关联数据 2. **索引优化** - 为常用查询字段建立索引 - 使用复合索引支持多条件查询 3. **连接池配置** - 配置合适的连接池大小 - 设置超时和重试机制 ### 关系查询最佳实践 ```mermaid flowchart TD Start([开始查询]) --> Choose["选择查询策略"] Choose --> |简单查询| Lazy["使用懒加载"] Choose --> |复杂查询| Eager["使用急加载"] Lazy --> Check["检查N+1问题"] Check --> |存在| Fix["修复为急加载"] Check --> |不存在| Optimize["优化查询"] Eager --> Selective["选择性加载"] Selective --> Filter["应用过滤条件"] Filter --> Result["返回结果"] Optimize --> Result Fix --> Result ``` **优化建议**: - 对于API响应,优先使用急加载确保一次性获取所需数据 - 对于后台任务,使用懒加载减少内存占用 - 合理使用索引提高查询性能 - 避免不必要的关联查询 ## 故障排除指南 ### 常见关系问题 1. **循环依赖问题** ```python # 解决方案:延迟导入 from app.models.models import Department # 在文件末尾导入 ``` 2. **自关联关系冲突** ```python # 解决方案:使用remote_side参数 parent: Mapped[Optional["Department"]] = relationship("Department", remote_side=[id], backref="children") ``` 3. **多重外键关系** ```python # 解决方案:明确指定foreign_keys assessor: Mapped[Optional["Staff"]] = relationship("Staff", foreign_keys=[assessor_id]) reviewer: Mapped[Optional["Staff"]] = relationship("Staff", foreign_keys=[reviewer_id]) ``` ### 数据一致性保证 1. **外键约束检查** - 确保引用的记录存在 - 验证级联删除行为 2. **事务管理** - 使用异步事务确保原子性 - 合理的回滚策略 **章节来源** - [models.py](file://backend/app/models/models.py#L169-L173) - [assessment_service.py](file://backend/app/services/assessment_service.py#L117-L118) ## 结论 本系统通过精心设计的数据模型关系映射,成功实现了复杂的医院绩效管理业务需求。主要特点包括: 1. **清晰的关系设计**:通过一对一、一对多、多对多关系准确反映业务实体间的联系 2. **完善的约束机制**:外键约束、检查约束确保数据完整性 3. **灵活的查询策略**:结合懒加载和急加载满足不同场景需求 4. **可扩展的架构**:模块化设计支持功能扩展和维护 系统在保证数据一致性的前提下,提供了良好的性能表现和可维护性,为医院绩效管理提供了坚实的技术基础。