Files
easygoadmin-wiki/EasyGoAdmin_Gin_NaiveVue/zh/guide/database.md
T
2026-10-25 17:24:27 +08:00

68 lines
3.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 3.2 数据库建表
:::tip 概述
表是模块开发的起点。本页以 `gin_example` 为例说明建表规约:命名、公共审计字段、索引与租户列的取舍。
:::
## 示例表结构
```sql
-- internal/repository/example.go 对应表
CREATE TABLE `gin_example` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(255) NOT NULL COMMENT '案例名称',
`avatar` varchar(255) NULL DEFAULT NULL COMMENT '案例图片',
`type` int NULL DEFAULT 0 COMMENT '案例类型:1-类型1 2-类型2 3-类型3 4-类型4',
`status` int NULL DEFAULT 0 COMMENT '案例状态:1-在用 2-停用',
`sort` int NULL DEFAULT 0 COMMENT '案例排序',
`create_user` varchar(50) NULL DEFAULT NULL COMMENT '创建人',
`create_time` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_user` varchar(50) NULL DEFAULT NULL COMMENT '更新人',
`update_time` datetime NULL DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
`del_flag` int NULL DEFAULT 0 COMMENT '删除标识:0-正常 1-已删除',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_gin_example_del_flag`(`del_flag` ASC) USING BTREE,
INDEX `idx_gin_example_name`(`name` ASC) USING BTREE,
INDEX `idx_gin_example_status`(`status` ASC) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '案例演示表';
```
## 公共审计字段
所有业务表统一带以下字段,**业务代码不手工赋值**——全局 Create/Update 钩子自动补齐:
| 字段 | 补齐方 | 说明 |
|---|---|---|
| create_user / create_time | Create 钩子 | 创建人 / 创建时间 |
| update_user / update_time | Update 钩子 | 更新人 / 更新时间 |
| del_flag | Create 钩子 | 默认 0;删除一律置 1 |
| tenant_id | Create 钩子 | 仅租户级表需要 |
## 租户列取舍
| 表类型 | 是否带 tenant_id | 示例 |
|---|---|---|
| 租户级表 | 带,且必须在 hooks 租户白名单内(共 9 张:user/role/dept/level/position/article/category/notice/link) | gin_article |
| 平台级表 | 不带 | gin_example、gin_dict、gin_param |
不带 tenant_id 的表不做租户隔离过滤,适合全局配置、字典、示例类数据。新表若需租户隔离,需同步把表名加入 `internal/model/hooks` 的租户白名单——两处不一致会导致隔离失效。
## 建表要点
| 要点 | 说明 |
|---|---|
| 主键 | 统一 `id` INT 自增,不用其他类型主键 |
| 字符集 | utf8mb4(兼容 emoji 与生僻字) |
| 索引 | 查询高频列建普通索引;命名 `idx_{表}_{列}`;唯一约束命名 `uk_{表}_{列}` |
| 注释 | 每列必须有 COMMENT;枚举列在注释中列出取值与含义(如 `1-在用 2-停用`),生成器与文档依赖它 |
| 软删 | 不建外键(软删除 + 应用层维护引用完整性) |
| 时间 | datetime;写入由钩子负责,查询无需关心时区(应用统一 Asia/Shanghai) |
## 枚举列与字典
示例表的 `type`/`status` 是整型枚举列,显示名由**系统字典**维护(如 `example_status`),读侧经 `SerializeMaps` 声明自动回填 `{field}Text` 字段。建表时只需保证注释中的取值与字典项一致,见 [3.5 业务层开发(service)](/zh/guide/service.html)。
## 下一步
→ [3.3 契约层开发(dto)](/zh/guide/dto.html)