Getting Count for Query with Filters, Order etc. #177
-
I'm trying to get a count for an existing query (using I cannot seem to figure out how to do it, despite it originally thinking it would be very simple. The query looks something like this (shortened example) : query := models.Users.Query(
ctx, db,
sm.Distinct(),
sm.InnerJoin(...),
sm.InnerJoin(...),
sm.InnerJoin(...),
sm.InnerJoin(...),
sm.Where(...),
sm.Where(...),
sm.Offset(...),
) Originally I thought I could just get the count, then apply some extra query mods to get the paginated results. Something like this: users, err := query.Count()
query.Apply(sm.Columns(..., ..., etc)
query.Apply(sm.OrderBy(models.UserColumns.Name))
query.Apply(sm.Limit(50))
users, err := query.All() However, this order doesn't work, as the count is not replaced with the column names when calling SELECT DISTINCT count(1), "users"."name" FROM "users" AS "users" ORDER BY "users"."name" LIMIT 50 OFFSET 0 which results in the error So I tried it the other way around (get the results first, then get the count). It works in this order without the I'm not sure if I'm not understanding something, or if I should be doing this a completely different way, or if there is a problem with how Any insight would be appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I have considered removing the What One solution would be to clone the query before issuing a |
Beta Was this translation helpful? Give feedback.
I have considered removing the
Count
method since it may not work how you would expect.What
Count
does is overwrite any selected columns with SELECT COUNT(1) and add .... LIMIT 1 before making the query. And since this modifies the original query, it can lead to unexpected issues like this.One solution would be to clone the query before issuing a
Count
that way the original query is not modified at all. We could then do other things like drop theORDER BY
which would have no effect on such a query anyway.