与 Sequelize 的嵌套关系

2022-01-19 00:00:00 javascript mysql sequelize.js

我正在使用带有 Node + MySQL 的 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!

推荐答案

Sequelize Docs: Nested Eager Loading

示例

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

相关文章