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

Sequelize多对多关联查询未返回嵌套关联数组问题求解

问题解决方案

核心原因

输出不符合预期是三个问题共同导致的:

  • raw: true 参数会强制返回数据库原始JOIN结果,多对多关联查询时,数据库原生返回的就是每个关联Commune对应一行CodePostal数据,Sequelize在raw模式下不会自动合并相同主表记录的关联数据到数组中
  • nest: true 参数的位置写错了,你错误将它放到了include数组内部,应该是查询配置的顶层参数
  • 没有配置隐藏中间表字段,所以返回了多余的R_Commune_CodePostal对象

推荐修复方案(无需手动处理数据)

去掉raw: true配置,Sequelize会自动完成关联数据的组装,同时配置排除中间表字段:

// 先调整关联定义,增加别名和创建、查询的配置对齐
CodePostal.belongsToMany(Commune, {through: R_Commune_CodePostal, as: 'communes'});
Commune.belongsToMany(CodePostal, {through: R_Commune_CodePostal});

// 查询代码
const queryResult = await CodePostal.findAll({
  include: [{
    model: Commune,
    as: 'communes',
    through: { attributes: [] } // 不返回中间表的任何字段
  }]
});
// 转换为普通JSON对象,即符合你预期的输出格式
const formattedResult = queryResult.map(item => item.toJSON());

如果你必须保留raw: true的场景

可以手动对原始结果做分组合并:

const rawResult = await CodePostal.findAll({
  raw: true,
  nest: true,
  include: [{
    model: Commune,
    as: 'communes',
    through: { attributes: [] }
  }]
});

// 手动按邮政编码分组,合并关联的公社数据
const mergedResult = Object.values(rawResult.reduce((groupMap, currentRow) => {
  const postalCode = currentRow.codePostal;
  if (!groupMap[postalCode]) {
    groupMap[postalCode] = {
      codePostal: postalCode,
      communes: []
    };
  }
  groupMap[postalCode].communes.push(currentRow.communes);
  return groupMap;
}, {}));

内容的提问来源于stack exchange,提问作者Wapax

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:36:01