You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:25:01