Node.js 复杂关系的续集与查询

Node.js 复杂关系的续集与查询,node.js,sequelize.js,Node.js,Sequelize.js,我试图了解如何最好地使用Sequelize和Node.js对多个实体执行查询 我定义了一个模型“User”,它与模型“Location”具有归属关系。然后我有一个模型“资产”,它也与“位置”有归属关系。当我有一个用户实例时,我希望获取与该用户关联的位置关联的所有资产 我尝试了以下似乎不起作用的方法 user.getLocations().then(function(userLocations) { return Asset.findAll({ where: { "Locations" : { $

我试图了解如何最好地使用Sequelize和Node.js对多个实体执行查询

我定义了一个模型“User”,它与模型“Location”具有归属关系。然后我有一个模型“资产”,它也与“位置”有归属关系。当我有一个用户实例时,我希望获取与该用户关联的位置关联的所有资产

我尝试了以下似乎不起作用的方法

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,
        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...
});

这是最后的结果

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...
});

谢谢这让我找到了正确的方向。除此之外,我还必须在“include”中明确指定“as”,因为我在定义关系时指定了“as”。此外,由于资产和位置之间存在一对多关系,因此在查询资产时必须包含位置。我会附上最后的问题作为单独的答案。谢谢。这让我找到了正确的方向。除此之外,我还必须在“include”中明确指定“as”,因为我在定义关系时指定了“as”。此外,由于资产和位置之间存在一对多关系,因此在查询资产时必须包含位置。我将附加最后一个问题作为单独的答案。