我正在努力了解如何最好地使用Sequelize和Node.js对多个实体执行查询。
我定义了一个模型"User",它与一个模型(Location)有一个belongsToMany关系。然后我有一个模型"资产",它也与"位置"有一个belongsToMany关系。当我有一个用户的实例时,我想获取与该用户关联的位置关联的所有资产。
我尝试了以下似乎不起作用。。。
user.getLocations().then(function(userLocations) { return Asset.findAll({ where: { "Locations" : { $any : userLocations } }) })
有人能提出什么建议吗?
尝试此查询:
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...
});
这是最终结果。。。
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...
});