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

如何将Sequelize返回的多表JSON数据合并为嵌套对象?

解决方案

方法1:手动合并查询结果

如果已经分别从四个表获取到了数据(Sequelize实例或纯JSON对象),直接构建目标嵌套结构即可:

// 假设已通过Sequelize获取各表数据
const staff = await Staff.findByPk(1); // Sequelize实例
const location = await Location.findByPk(1);
const service = await Service.findByPk(1);
const tenant = await Tenant.findByPk(1);

// 合并为嵌套对象
const combinedData = {
  staff: staff?.toJSON() || null, // 用toJSON()将Sequelize实例转为纯JS对象
  location: location?.toJSON() || null,
  service: service?.toJSON() || null,
  tenant: tenant?.toJSON() || null
};

// 如果查询时使用了{ raw: true }选项,直接赋值即可
// const combinedData = { staff, location, service, tenant };

方法2:利用Sequelize关联查询直接生成嵌套结构

如果四个表之间存在外键关联(比如Tenant关联Location、Service、Staff),可以通过include选项一次性查询并返回嵌套结构,减少数据库请求次数:

  1. 首先确保模型间已定义关联,例如在Tenant模型中:
// Tenant.model.js
Tenant.hasOne(Location, { as: 'location', foreignKey: 'tenantId' });
Tenant.hasOne(Service, { as: 'service', foreignKey: 'tenantId' });
Tenant.hasOne(Staff, { as: 'staff', foreignKey: 'tenantId' });
  1. 查询时关联其他表:
const tenantWithRelations = await Tenant.findByPk(tenantId, {
  include: [
    { model: Location, as: 'location' },
    { model: Service, as: 'service' },
    { model: Staff, as: 'staff' }
  ]
});

// 转换为纯嵌套对象
const combinedData = tenantWithRelations.toJSON();

// 如果需要将Tenant数据也作为顶层key,可调整结构:
const finalData = {
  tenant: { ...combinedData, location: undefined, service: undefined, staff: undefined },
  location: combinedData.location,
  service: combinedData.service,
  staff: combinedData.staff
};

注意事项

  • 如果查询可能返回null(比如对应ID不存在),使用可选链?.和默认值|| null避免报错。
  • 若不需要Sequelize实例的方法,查询时添加{ raw: true }选项可直接获取纯JSON对象,省略toJSON()步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:41:06