在数组中的子项中找到父项

时间:2018-09-17 20:17:42

标签: javascript sql sequelize.js

我有两个桌子

  1. 地点
  2. 产品

我要实现的目标是通过多个 产品 查找 地点 。 所以基本上。

find PLACE where product ids in [1,4,6]

问题是,它会寻找产品ID = 1或ID = 4的每个地方。我想找到一个包含所有产品的地方。因此必须满足3个条件。

这是续集的样子

const eq = await Place.findAndCountAll({
  include: [
    {
      model: PlaceProduct,
      as: 'products',
      where: {
        productId: [1,2,5]
      }
    },
  ],
}

它返回仅包含必需产品的位置。

我希望所有这些都是必需的。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以检查记录数是否与product_ids相同,如果是,则是您想要的记录,如果少于该记录,它将被忽略

const product_ids = [1, 2, 5];

const eq = await Place.findAll({
    include: [{
        model: PlaceProduct,
        attributes : [],
        as: 'products',
        where: {
            productId: product_ids // <----- product_ids
        }
    }, ],
    group: ['place.id'], // <--- Not sure but , you might need to add place_product.id also here
    having: {
        $and: [
            db.sequelize.where(db.sequelize.fn('count', db.sequelize.col('place.id')), product_ids.length), // <----- product_ids
        ]
    }
}