3.2 KiB
3.2 KiB
Association Eager-Loading 与 N+1 规约
更新时间: 2026-03-23 适用阶段: Model 重构阶段 4.4 范围: app/service/**/*.js 中涉及 Sequelize 关联查询的代码
1. 目标
- 降低关联查询的 SQL 次数与响应时间抖动。
- 统一 eager-loading 写法,避免 include 漂移导致错关联。
- 在不改变外部接口返回结构的前提下收敛查询成本。
2. 术语
- eager-loading: 通过 include 一次性加载关联数据。
- N+1: 先查 1 次主数据,再按每条主数据各查 1 次关联,导致总查询次数随 N 线性增长。
- 关联上下文约束: 在 include.where 中补齐业务维度(如 warehouse_id、use_status),避免跨上下文错关联。
3. 强制规则
- 列表查询禁止在循环内按行查询关联表。
- 只要关联数据是展示必需字段,优先使用 include 一次加载。
- include 必须显式声明 attributes,禁止默认全字段拉取。
- include 需要业务上下文约束时,必须补齐 where 条件(典型: warehouse_id + use_status)。
- hasMany/hasOne/belongsTo 的 as 必须与 model 定义一致,禁止临时字符串别名。
- 分页列表若包含 hasMany,优先控制返回列并评估 distinct/subQuery,防止计数与分页漂移。
- count 与 findAll 不一致时,必须拆分并保持 where/include 语义一致。
4. 推荐写法
4.1 反模式(N+1)
const list = await Model.findAll({ where });
for (const row of list) {
row.child = await Child.findOne({ where: { id: row.child_id } });
}
4.2 规约写法(eager-loading)
const list = await Model.findAll({
where,
attributes: [ 'id', 'name', 'child_id' ],
include: [
{
model: Child,
as: 'child',
attributes: [ 'id', 'name' ],
required: false,
},
],
});
4.3 仓库维度约束(本仓库高频场景)
include: [
{
model: ctx.model.StoreWarehouse,
as: 'store_stock',
attributes: [ 'store_id', 'store_remask' ],
where: {
warehouse_id: warehouseId,
use_status: 1,
},
required: false,
},
]
5. 当前代码落地点
- receiving 链路已按规约补齐仓库维度过滤,避免 StoreWarehouse 跨仓匹配。
- receiving 与 receiving_detail 已移除无效 Storage hasMany 关联,避免误导 include 设计。
- 后续优先治理:
- store_warehouse 与 stock_warehouse 的 store_id 语义对齐
- role / role_permission / permission 的关联约束与 include 一致性
6. 变更门禁
每批涉及关联查询的改动,至少执行以下门禁:
- node .\script\method-output-regression.cjs compare
- node .\script\tmp-generate-method-regression-test.cjs
- npx egg-bin test temp/generated-tests/system.method-output.generated.test.js
- npx egg-bin test test/app/controller/system.user.login.test.js test/app/controller/system.user.info.test.js test/app/controller/home.test.js
交付标准:
- compare 结果 mismatch=0
- 生成回归与关键冒烟测试全部通过
7. PR 自检清单
- 是否存在循环内数据库查询。
- include 是否补齐 attributes。
- include.where 是否补齐业务上下文约束。
- as 是否与 model 关联定义一致。
- 是否完成 method-output compare 与回归测试。