简体   繁体   English

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

[英]Find parent where child in array

I've got two tables, 我有两张桌子,

  1. Places 地方
  2. Products 制品

What I am trying to achieve is to find Place By multiple products . 我要实现的目标是找到Place By多个产品 So basically. 所以基本上。

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

The thing is that it looks for every place where product id = 1 OR id = 4. I want to find a place that contains all the products. 事实是,它会寻找产品ID = 1或ID = 4的每个地方。我想找到一个包含所有产品的地方。 So 3 conditionals must be achieved. 因此必须满足3个条件。

This is how it looks in sequelize 这就是续集的样子

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

And it returns places which contain only of the required products. 并且它返回仅包含必需产品的位置。

I want all to be required. 我想要所有的东西。

Thanks! 谢谢!

You can check the count of records are exact of product_ids , if yes then thats the record you want , and if is less than that it will be ignored 您可以检查记录数是否与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
        ]
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM