Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
Sequelize filter based on JOIN results

I have a table orders which have a belongs to many relationship to categories. i.e. 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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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,
    },
  ],
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda