Domi
Domi

Reputation: 24508

Nested relations with Sequelize

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!

Upvotes: 43

Views: 47638

Answers (3)

Abhimanyu Singh
Abhimanyu Singh

Reputation: 31

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
    }
  }

Upvotes: 0

Gaurav Badarkhe
Gaurav Badarkhe

Reputation: 9

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;
}

Upvotes: 0

Jan Aagaard Meier
Jan Aagaard Meier

Reputation: 28778

Sequelize Docs: Nested Eager Loading

Example

Issue.find({
    include: [
        {
            model: Invite,
            include: [Group]
        }
    ]
});

Upvotes: 113

Related Questions