Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 910
Domi Avatar asked Jun 18 '14 10:06

Domi


People also ask

What is nested in Sequelize?

Sequelize allows you to join a third table that's related to the second table by creating a nested include. For example, suppose you have three tables with the following relations: The Users table has one-to-many relation with the Invoices table. The Invoices table has many-to-one relations with the Users table.

How do you do a one-to-many relationship in Sequelize?

Creating the standard relationships​ To create a One-To-One relationship, the hasOne and belongsTo associations are used together; To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.


1 Answers

Sequelize Docs: Nested Eager Loading

Example

Issue.find({
    include: [
        {
            model: Invite,
            include: [Group]
        }
    ]
});
like image 52
Jan Aagaard Meier Avatar answered Oct 06 '22 10:10

Jan Aagaard Meier