crotoan
crotoan

Reputation: 183

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. 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. So 3 conditionals must be achieved.

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!

Upvotes: 0

Views: 264

Answers (1)

Vivek Doshi
Vivek Doshi

Reputation: 58593

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

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
        ]
    }
}

Upvotes: 1

Related Questions