【问题标题】:A single Sequelize query for querying an association that has an association用于查询具有关联的关联的单个 Sequelize 查询
【发布时间】:2020-04-13 20:59:29
【问题描述】:

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

Report.belongsTo(Branch);
Branch.belongsTo(Client);

在使用相关分支和客户端查询报表时,我运行 2 个查询:

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();

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

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 2016-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      相关资源
      最近更新 更多