【问题标题】:Sequlize how to do nested joinsSequelize 如何进行嵌套连接
【发布时间】:2018-08-21 10:35:21
【问题描述】:

我有四个模型。即

  1. 图片
  2. restaurant_items
  3. 餐厅
  4. 项目

images.belongsTo (restaurant_items)

这意味着我可以像这样获取与 图像 关联的所有 restaurant_items 表详细信息,

const all_approved_images = await db.images.findAll({
            where: {
                status: "approved"
            },
            include: ['res_item']
        })

但我想同时获得ITEM TABLE和RESTAURANT TABLE的详细信息

restaurant_items 属于餐厅

restaurant_items 属于项目

我试过了

const all_approved_images = await db.images.findAll({
            where: {
                status: "approved"
            },
            include: ['res_item','res','item']
        })

这没有奏效。说

不存在与别名“res”的关联

因为它不存在于 图片 但它与 restaurant_items

一起存在

应该有办法把所有这些东西联系起来。

我如何做到这一点?

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

    在这里,从嵌套级别获取数据:

    db.images.findAll({
        where: {
            status: "approved"
        },
        include: { 
            association: 'res_item' , // <---- First Level
            include : {
                association: 'res' , // <---- Second Level
                include : {
                    association: 'item' , // <---- Third Level
                }
            }
        }
    })
    

    【讨论】:

    • 非常感谢您。 =D 你拯救了这一天。我还有一件事要问。 =) 我如何过滤关联数据集。别名“res”为我提供了有关餐厅的所有详细信息,但我只想要 res_name 列。
    • 在此行后添加attributes : ['id','res_name'] association: 'res'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2020-04-23
    • 2023-03-03
    • 2015-10-07
    • 1970-01-01
    • 2013-04-17
    • 2013-12-25
    相关资源
    最近更新 更多