Reputation: 858
I'm fairly new to Sequelize, and I can't seem to find an answer to my question.
I have a model 'team' which has associations defined as:
team.hasMany(members, {foreignKey: 'memberId', onDelete: 'cascade'});
team.belongsTo(memberDetails, {as: 'type1', foreignKey: 'type1Id'});
team.belongsTo(memberDetails, {as: 'type2', foreignKey: 'type2Id'});
I want to load team rows from the database, and as I load each row I want the (some of) the associations to be included as well. I use the following code:
team.findAll({
include: [
{
model: memberDetails,
as: 'type1'
}
]
})
This loads the teams as expected, and loads associated members, and also loads and attaches details for 'type1' members per the include.
However, the memberDetail model also has associations:
memberDetails.belongsTo(memberInfo, {as: 'type1', foreignKey: 'type1Id'});
memberDetails.belongsTo(memberInfo, {as: 'type2', foreignKey: 'type2Id'});
What I want is the memberInfo associations to be loaded for each member loaded - similar to the INCLUDEd memberDetails, but I don't know how to specify the INCLUDE for the eagerly loaded associations.
Can anyone help?
Upvotes: 8
Views: 6107
Reputation: 903
You could do something like this, as explained in the Sequelize Doc about nested eager loading.
team.findAll({
include: [{
model: memberDetails,
as: 'type1Details',
include: [{
model: memberInfo,
as: 'type1Info'
}]
}]
});
Upvotes: 13