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

Sequelize查询为何未将关联模型以嵌套对象形式返回?

问题:Sequelize关联查询返回结构不符合预期

我有两个关联模型:TariffsModel和PoliciesModel,PoliciesModel通过tariff_id关联到TariffsModel的特定记录。关联本身有效,但Sequelize的查询结果不符合预期:

预期返回结构

PoliciesModel {
   id: 1,
   owner_party_id: 2,
   tariff: {
      id: 1,
      is_active: true,
      ...
   },
   ...
}

实际返回结构

PoliciesModel {
   id: 1,
   owner_party_id: 2,
   tariff.id: 1,
   tariff.is_active: true,
   ...
}

关联初始化代码

const {
            PoliciesModel,
            TariffsModel,
        } = this.sequeluze.models;

        PoliciesModel.belongsTo(TariffsModel, { foreignKey: 'tariff_id', as: 'tariff' });

查询代码

const policies = await PoliciesModel.findAll({
            where: { owner_party_id: userAccount.party_id },
            include: {
                model: TariffsModel,
                as: 'tariff',
            },
            raw: true,
        });

我尝试过使用hasMany/hasOne方法及as参数,但问题仍未解决,请问该问题的原因是什么?


原因及解决方案

问题原因

你在查询时启用了raw: true配置,该配置会让Sequelize直接返回数据库查询的扁平化原始结果,不会将关联模型的数据自动嵌套为对象结构,这就导致tariff的字段以tariff.id这种拼接键名的形式呈现,而非预期的嵌套对象。

解决方案

有两种方式可以解决这个问题:

  1. 移除raw: true:
    去掉该配置后,Sequelize会默认返回模型实例对象,关联的tariff数据会自动嵌套为预期的对象结构:

    const policies = await PoliciesModel.findAll({
                where: { owner_party_id: userAccount.party_id },
                include: {
                    model: TariffsModel,
                    as: 'tariff',
                }
            });
    
  2. 保留raw: true并添加nest: true:
    如果你确实需要原始数据格式但希望保留嵌套结构,可以同时启用nest: true配置,它会将扁平化的键名自动解析为嵌套对象:

    const policies = await PoliciesModel.findAll({
                where: { owner_party_id: userAccount.party_id },
                include: {
                    model: TariffsModel,
                    as: 'tariff',
                },
                raw: true,
                nest: true
            });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:05:20