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

429
Vistas
Count related models and limit using Sequelize

I have a working Sequelize query that get models including the count of related models in this way:

    const elements = await ElementsModel.findAll({
      attributes: {
        include: [[Sequelize.fn("COUNT", Sequelize.col("related.id")), "related_total"]]
      },
      include: [
        {
          model: RelatedModel,
          attributes: [],
        }
      ],
      group: ['elements.id']
    });

The query works great, but now I need to include an offset and limit clause for pagination like:

    const elements = await ElementsModel.findAll({
      limit: 10,
      offset: 0,
      attributes: {
        include: [[Sequelize.fn("COUNT", Sequelize.col("related.id")), "related_total"]]
      },
      include: [
        {
          model: RelatedModel,
          attributes: [],
        }
      ],
      group: ['elements.id']
    });

And the query breaks and is not working anymore because of the combination of the included field and the limit clause, generating an invalid query like:

SELECT `elements`.* 
FROM (
  SELECT `elements`.`id`, `elements`.`type`, COUNT(`related`.`coupon_id`) AS `related_total` 
  FROM `elements` AS `elements` GROUP BY `elements`.`id` LIMIT 0, 20
) AS `elements` 
LEFT OUTER JOIN `related` AS `related` ON `elements`.`id` = `related`.`elements_id`;

There is some way to handle this with Sequelize?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

To use limit and offset options properly you need to use a subquery with Sequelize.literal instead of Sequelize.fn and remove the include and group options at all.

const elements = await ElementsModel.findAll({
      limit: 10,
      offset: 0,
      attributes: {
        include: [
  // correct a table name and fields if needed
  [Sequelize.literal("(SELECT COUNT(*) FROM Related where Related.elementId=Elements.id)"), "related_total"]
      ]
      },
    });
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