我正在尝试了解如何最好地使用Sequelize和Node.js对多个实体执行查询。
我已经定义了一个模型“User”,它与一个模型“Location”具有belongsToMany关系。然后我有一个模型“资产”,它与“位置”也有一个belongsToMany关系。当我有一个用户实例时,我想获取与用户关联的位置相关联的所有资产。
我尝试了以下似乎不起作用的......
{{1}}
有人可以提出任何建议吗?
答案 0 :(得分:1)
尝试此查询:
User.findById(user_id, {
include: [{
model: Location,
required: true
}]
}).then(user => Asset.findAll({
where: {
user_id: user.id,
location_id: {
$in: user.locations.map(location => location.id)
}
}
})).then(assets => {
// The rest of your logic here...
});
答案 1 :(得分:0)
这是最后的结果......
User.findById(user_id, {
include: [{
model: Location,
as: 'Locations', // Was needed since the original relation was defined with 'as'
required: true
}]
}).then(user => Asset.findAll({
include: [{
model: Location,
as: 'Locations',
where: {
id: {
$in: user.Locations.map(location => location.id)
}
}
}]
})).then(assets => {
// The rest of your logic here...
});