Adding limit: to findAll() DESTROYS the query
See original GitHub issueI’m trying to return a group of Model
s, paginated using limit
and offset
, including the grouped count of that model’s favorites. A fairly trivial thing to attempt.
Here’s my basic query setup with sequelize:
var perPage = 12;
var page = 1;
return Model.findAll({
group: [ 'model.id', 'favorites.id' ],
attributes: [
'*',
[ Sequelize.fn('count', Sequelize.col('favorites.id')), 'favorites_count' ]
],
include: [
{ attributes: [], model: Favorite },
],
offset: perPage * page
This generates the (fairly) expected query:
SELECT "model"."id",
"model".*,
Count("favorites"."id") AS "favorites_count",
"favorites"."id" AS "favorites.id"
FROM "model" AS "model"
LEFT OUTER JOIN "favorite" AS "favorites"
ON "model"."id" = "favorites"."model_id"
GROUP BY "model"."id",
"favorites"."id" offset 12;
Ignoring the fact that it quotes the tables, and that it selects favorites.id
(forcing me to add it to the group by clause), and that it has randomly aliased things to their exact name or to a nonsensical name like "favorites.id"
(all undesired), it seems to have worked. But now let’s complete the pagination and add the limit to the query:
...
offset: perPage * page
limit: perPage
It now generates this query:
SELECT "model".*,
"favorites"."id" AS "favorites.id"
FROM (SELECT "model"."id",
"model".*,
Count("favorites"."id") AS "favorites_count"
FROM "model" AS "model"
GROUP BY "model"."id",
"favorites"."id"
LIMIT 12 offset 12) AS "model"
LEFT OUTER JOIN "favorite" AS "favorites"
ON "model"."id" = "favorites"."model";
In completely baffling behavior, it has generated an inner query and applied the limit only to that, then aliased that as "model"
.
As a sanity check I looked in the docs for findAll, but the docs do not seem to think that command exists.
I suspect I am doing something wrong, but I can’t figure out what it is. This behavior is quite bizzarre, and I’m hoping my sleep deprivation is the cause of my confusion.
I’m using version 2.0.6
Issue Analytics
- State:
- Created 8 years ago
- Reactions:1
- Comments:9 (5 by maintainers)
It dawns on me that you are doing an aggregate and simply ignoring the attributes from the joined table. And in that case, you are right, the LIMIT could simply be appended, but i’m afraid Sequelize is not smart enough to detect that case at the moment.
We have however had a few discussions about providing a
subQuery: false
flag to the query to turn off the subquery behaviour manually when absolutely needed.@krisr I plan to start working on a
seperate: true
feature for includes soon that would allow a user to split that part of the tree into a seperate query, for performance and fixes.