简体   繁体   English

基于 JOIN 结果的 Sequelize 过滤器

[英]Sequelize filter based on JOIN results

I have a table orders which have a belongs to many relationship to categories .我有一个表orders ,它与categories有很多关系。 ie an order can have the categories food , fruit , banana all at the same time.即一个订单可以同时拥有foodfruitbanana的类别。

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.例如,给我所有具有food类别的订单。 This would be simple if I'm happy with getting the order including only the food category in the JOIN.如果我对获得仅包含 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.我还尝试将 where 语句放在父级上。

{ '$categories.id$': 'a437ffab-5085-4fd7-b193-23dfb299aa39' } But I guess it's essentially the same. { '$categories.id$': 'a437ffab-5085-4fd7-b193-23dfb299aa39' }但我想它本质上是一样的。

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.编辑:根据评论的建议,我为此编写了原始 SQL,这可能会使尝试将其转换为 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.现在的问题是如何使用 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,
    },
  ],
})

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

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