Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda