用于查询具有关联的关联的单个Sequelize查询

时间:2019-05-10 10:53:49

标签: sequelize.js

我有3个模型:报表,分支,客户端。

Report.findOne({
        where:{id:reportId},
        include: [{
            model: Branch,
            attributes: ['name','clientId']
        }]
    })
        .then((report)=>{
            const clientId = report.dataValues.branch.clientId;
            Client.findOne({
                where:{id:clientId},
            })
                .then((client)=>{
                    console.log('client is ', client);

                });


        })
        .catch();

在查询具有相关分支和客户端的报表时,我会运行2个查询:

{{1}}

我只能使用一个连接Report-> Branch-> Client的查询来查询数据吗?

1 个答案:

答案 0 :(得分:1)

是的,includes可以相互嵌套。假设关联Branch.belongsTo(Client);设置正确,您应该可以做到:

Report.findOne({
    where: {
        id: reportId
    },
    include: [
        {
            model: Branch,
            attributes: [ 'name', 'clientId' ],
            include: [
                {
                    model: Client
                }
            ]
        }
    ]
});