简体   繁体   中英

Why doesn't sequelize include associated model to a nested object in the results?

I have two associated models: TariffsModel and PoliciesModel. PoliciesModel has tariff_id which refers to specific tariff by its ID. And this works but Sequelize returns the result in a weird way: instead of returning:

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

it returns:

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

Here's the example: enter image description here

I initiate the relation like this:

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

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

and make the query like this:

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

What could be the reason of this kind of behavior?

I tried calling hasMany/hasOne methods and using as parameter, but it didn't help.

In your Sequelize query, if you remove the property raw then you get the response as expected.

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

The query should be like the following one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM