如何在Sequelize关联查询中避免属性嵌套结构?
如何通过Sequelize直接获取平级结构的查询结果
当然可以通过Sequelize本身实现,无需后续用JavaScript修改对象。核心思路是在查询的attributes中直接指定关联模型的字段,并避免Sequelize生成嵌套的关联结构,以下是两种可行方案:
方案一:显式指定关联字段并隐藏关联模型的默认返回
这种方法保留Sequelize模型实例的特性(如果需要后续调用模型方法),同时返回平级结构:
await this.myModel.findAll({ attributes: [ 'someAttribute', // 用sequelize.col引用关联表的字段,并重命名为目标平级字段名 [sequelize.col('anotherModel.attributesFromAnotherModel'), 'attributesFromAnotherModel'] ], include: [{ model: anotherModel, attributes: [] // 空数组表示不返回关联模型的嵌套结构 }] })
执行后会直接得到你想要的平级结果:
{ "someAttribute": "some data", "attributesFromAnotherModel": "some data" }
方案二:使用raw: true返回纯平级JSON
如果不需要Sequelize模型实例,只需要纯数据对象,可以结合raw: true参数:
await this.myModel.findAll({ attributes: [ 'someAttribute', [sequelize.col('anotherModel.attributesFromAnotherModel'), 'attributesFromAnotherModel'] ], include: [{ model: anotherModel, attributes: [] }], raw: true // 返回纯JSON对象,而非模型实例 })
注意事项
- 确保
anotherModel和myModel的关联关系已正确定义(比如一对一关联),如果是一对多关联,平级结果会出现重复的主表数据,需要结合group或后续去重处理。 - 原查询代码中
include前缺少逗号,属于语法错误,需要修正后才能正常执行。
内容的提问来源于stack exchange,提问作者Fabian
相关产品推荐
相关产品推荐

