代码之家  ›  专栏  ›  技术社区  ›  weeraa

使用join少数表Sequelize ORM获取不同的数据

  •  1
  • weeraa  · 技术社区  · 7 年前

    这是关于sequelize ORM的,我正在为MEIN应用程序开发节点JSAPI。 米价表 (FK:mealId) 链接到餐桌 (主键:Id) ,餐桌 (FK:餐厅) 链接到餐厅餐桌 (主键:Id) 。“mealprice”表没有直接连接到“restaurant”表。 我需要的是,如果我将“IsActive=true”状态传递给mealPrice表,并且应该得到餐厅(不同列表)列表。老实说,我对sequelize ORM没有太多经验。这是我到目前为止尝试的,它返回米饭和膳食数据。

            global.mealpricing.belongsTo(global.meal, { targetKey: 'id', foreignKey: 'mealId' });
            global.meal.belongsTo(global.resturant, { targetKey: 'id', foreignKey: 'resturantId' });
    
            global.mealpricing.findAll({
                include: [{
                    model: global.meal,
                }],
    
                where: { isActive: true }
            }).then(meals => {
                res.send(meals);
            });
    

    我关心的是如何获得JSON唯一餐厅的独特列表?请给我一个方向。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Abhishek Agarwal    7 年前
    • 使用的内部连接获取所有餐厅ID 计量定价 具有 一餐 桌子
    • 使用“id”列上的distinct运算符,通过这些id查找所有餐厅

      global.mealpricing.findAll({ 
       where: {isActive: true},
       include: {
         model: global.meal,
         attributes: ['resturantId']
       }
      })
      .then(mealPricingDocs => {
        const restaurantIds = mealPricingDocs.map(i => i.meal.restaurantId);
        return global.restaurant.findAll({
         where: { id: { $in: restaurantIds } },
         distinct: 'id'
        });
      })
      .then(restaurants => res.send(restaurants));
      
    推荐文章