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

Sequelize如何查询多对多中间表并同步获取另外两张关联表的数据

Sequelize多对多关联查询解决方案

第一步:补全关联关系

你目前仅定义了Company和Event之间的多对多关联,要实现以中间表为主体返回关联数据,需要额外补充中间表与两个主表的一对一关联:

// 追加关联声明
CompanyEvent.belongsTo(Company, {
  foreignKey: 'companyId',
  as: 'company'
});
CompanyEvent.belongsTo(Event, {
  foreignKey: 'eventId',
  as: 'event'
});

第二步:编写查询语句

直接以中间表CompanyEvent为查询主体,通过include引入关联的两个主表数据即可:

const result = await CompanyEvent.findAll({
  // 可按需添加where条件过滤指定关联记录,例:
  // where: { companyId: 1, eventId: 1 },
  attributes: ['companyId', 'eventId'],
  include: [
    {
      model: Company,
      as: 'company',
      attributes: ['id', 'name', 'description']
    },
    {
      model: Event,
      as: 'event',
      attributes: ['id', 'name']
    }
  ]
});
// 如需转换为普通JSON对象,可追加toJSON调用
const formattedResult = result.map(item => item.toJSON());

注意不要开启查询参数的raw: true配置,否则会自动打平嵌套结构,无法得到分层的company、event对象。

查询结果会完全匹配你需要的输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:36:02