I am using Sequelize with Node + MySQL.
I have a model structure similar to this:
// models:
var Group, Issue, Invite;
// many Issues per Group
Group.hasMany(Issue);
Issue.belongsTo(Group);
// Groups can invite other Groups to work on their Issues
Issue.hasMany(Invite, {foreignKey: groupId});
Invite.belongsTo(Issue, {foreignKey: groupId});
Group.hasMany(Invite, {foreignKey: inviteeId});
Invite.belongsTo(Group, {foreignKey: inviteeId});
// given an Issue id, include all Invites + invited Groups (inviteeId) - But how?
var query = {
where: {id: ...},
include: ???
};
Issue.find(query).complete(function(err, issue) {
var invites = issue.invites;
var firstInvitedGroup = issue.invites[0].group;
// ...
});
Is this at all possible? What are possible work-arounds? Thank you!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Sequelize Docs: Nested Eager Loading
Example
Issue.find({
include: [
{
model: Invite,
include: [Group]
}
]
});
Method 2
If you want to eager load all nested associations use this function.
Issue.find({ include:getNestedAssociations(Issue) }); //Recursively load all bested associtiaons function getNestedAssociations(_model) { const associations = []; for (const association of Object.keys(_model.associations)) { const model = _model.associations[association].target; const as = association; const include = getNestedAssociations(model); associations.push({ model: model, as: as, ...(include && { include: include }), }); } return associations; }
Method 3
After loosing all the hopes, I lastly just tried one random hit snd that worked.
Just send attributes with empty array, then it wont be included in results
{ model: User, as: 'users', attributes: [], // This will work// where: { user_id: 1 } }
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0