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

Time:12-28

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.

CodePudding user response:

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.

  • Related