Reputation: 217
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 modelB
but the ModelB
does 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
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
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