我正在使用Sequelize与Node + MySQL。
我有一个类似的模型结构:
// 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;
// ...
});
这一切都可能吗?什么是可能的解决方案?谢谢!
答案 0 :(得分:80)
Sequelize Docs: Nested Eager Loading
示例强>
Issue.find({
include: [
{
model: Invite,
include: [Group]
}
]
});
答案 1 :(得分:0)
如果您想加载所有嵌套的关联,请使用此功能。
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;
}
答案 2 :(得分:0)
在失去所有希望之后,我终于尝试了一个有效的随机命中。 只发送带有空数组的属性,然后它就不会包含在结果中
{
model: User,
as: 'users',
attributes: [], // This will work//
where: {
user_id: 1
}
}