简体   繁体   中英

Sequelize filter based on JOIN results

I have a table orders which have a belongs to many relationship to categories . ie an order can have the categories food , fruit , banana all at the same time.

Order.belongsToMany(models.category, { through: 'orderCategory', as: 'categories' });

I want to make a query to get all orders that have at least one of the given categories. For example, give me all orders that have the food category. This would be simple if I'm happy with getting the order including only the food category in the JOIN. But I want to include all categories even if only one of them matches. So essentially I need to filter on values based on the left outer join result.

My query right now:

order.findAll({
  include: [
    {
      model: models.category,
      as: 'categories',
      where: {
        id: 'a437ffab-5085-4fd7-b193-23dfb299aa39',
      },
      // required: false,
    },
  ],
})

I've also tried to put the where statement on the parent.

{ '$categories.id$': 'a437ffab-5085-4fd7-b193-23dfb299aa39' } But I guess it's essentially the same.

One idea is to do the filtering after the fetch instead, but then I wouldn't be able to do proper limit and offset.

Edit: From a suggestion from a comment, I have written the raw SQL for this, which might make it easier to then try to translate it to Sequelize.

SELECT
    *
FROM
    orders
    JOIN order_categories ON order_categories.order_id = orders.id
WHERE
    orders.id in(
        SELECT
            order_id FROM order_categories
        WHERE
            order_categories.category_id = 'a437ffab-5085-4fd7-b193-23dfb299aa39')

I'm not sure if this is the most effective way, but it works. Now the question is how to do this with Sequelize.

let we have an order_id with name of order_id. then we can retrive data using this code 

order.findAll({
     where:{id:order_id},
  include: [
    {
      model: models.category,
      as: 'categories',
      where: {
        id: 'a437ffab-5085-4fd7-b193-23dfb299aa39',

      },
      // required: false,
    },
  ],
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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