Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading