Amaury Laroze
Amaury Laroze

Reputation: 217

Sequelize - Associate a model that is associated with another model

I'm tottaly new in NodeJS + Sequelize. I have a question about association.

I have 3 models :

I have two association :

ModelA.belongsTo(ModelB, {as: 'myModelB'});
ModelB.belongsTo(ModelC, {as: 'myModelC'});

Now, i get the ModelA:

router.get('/', (req, res) => {
ModelA.findAll({ include: [ 'myModelB' ]})
    .then(result => {
        res.json(result);
    })
    .catch(err => console.log(err))
});

In the response i only have the info of the modelBbut the ModelBdoes not have the info of ModelC

My result :

{
  id: 1,
  attr1: 'toto',
  attr2: 'tata',
  myModelB: {
               attrB1: 'Hello',
               attrB2: 'World',
               fk_modelC: 1
            }
}

The result i want :

{
  attr1: 'toto',
  attr2: 'tata',
  myModelB: {
               attrB1: 'Hello',
               attrB2: 'World',
               fk_modelC: {
                           attrC1: 'It',
                           attrC2: 'Works!'
                          }
            }
}

How can i include the ModelC in the ModelB when i use the ModelA?

Upvotes: 0

Views: 80

Answers (2)

ssbarbee
ssbarbee

Reputation: 1712

What you are after is: https://sequelize.readthedocs.io/en/latest/docs/models-usage/index.html#nested-eager-loading

Perhaps something like:

ModelA.findAll({ 
    include: [{
      model: ModelB, 
      as: 'myModelB', 
      include: [{
         model: ModelC,
         as: 'myModelC', 
      }]
   }]
 })
    .then(result => {
        res.json(result);
    })
    .catch(err => console.log(err))
});

Upvotes: 1

Riajul Islam
Riajul Islam

Reputation: 1483

Use this snipet:

router.get('/', (req, res) => {
    ModelA.findAll({
        include: {
            'myModelB',
            include: {
                'myModelC'
     }
        }
    })
        .then(result => {
            res.json(result);
        })
        .catch(err => console.log(err))
});

Upvotes: 0

Related Questions