
本文介绍如何使用 Sequelize 的 attributes 配置实现关联表字段的扁平化输出,避免默认生成的 Account.email 这类嵌套键名,直接将外键字段(如 email)作为顶层属性返回,无需多次查询或手动拼接对象。
本文介绍如何使用 sequelize 的 attributes 配置实现关联表字段的扁平化输出,避免默认生成的 `account.email` 这类嵌套键名,直接将外键字段(如 email)作为顶层属性返回,无需多次查询或手动拼接对象。
在使用 Sequelize 进行关联查询时,include 选项默认会将被包含模型的字段以 形式嵌套在结果对象中(例如 Account.email),这虽符合关系语义,但在 API 响应、前端消费或数据导出等场景下往往需要扁平化的字段结构(如直接为 email)。幸运的是,Sequelize 提供了灵活的 attributes 配置能力,完全可以在单次查询中实现字段扁平化,无需分步查询或手动合并对象。
核心思路是:
✅ 在根级 attributes.include 中显式声明需提升的关联字段(使用 Sequelize.col() 指向关联表列);
✅ 同时将 include 中被关联模型的 attributes 设为空数组 [],抑制其默认嵌套输出;
✅ 避免设置 raw: true(它会禁用属性映射逻辑,反而使 Sequelize.col() 失效)。
以下是推荐的完整写法:
const operator = await operatorService.findOne({
where: { id },
attributes: {
include: [
[Sequelize.col('Account.email'), 'email'] // 将 Account.email 映射为顶层 email 字段
]
},
include: [{
model: models.Account,
attributes: [] // 关键:清空被包含模型的字段列表,防止嵌套输出
}]
});
执行后,operator 对象将形如:
{
"id": 123,
"city": "Rockhill",
"firstName": "Livingston",
"email": "[email protected]"
}
⚠️ 注意事项:
-
不要启用
raw: true—— 它会绕过 Sequelize 的属性别名解析机制,导致Sequelize.col()无法正确映射字段; -
Sequelize.col('Account.email')中的Account是模型在include中注册的别名(即model: models.Account的默认别名),若自定义了as: 'account',则需改为Sequelize.col('account.email'); - 若需扁平化多个字段(如
email和balance),可在include数组中追加多项:[Sequelize.col('Account.email'), 'email'], [Sequelize.col('Account.balance'), 'balance']; - 此方法适用于
findOne、findAll、findAndCountAll等所有支持include和attributes的查询方法。
通过这一配置,你既能享受 Sequelize 关联查询的便利性与 SQL 优化能力,又能获得干净、符合接口规范的扁平化数据结构,真正实现“一次查询、开箱即用”。










