stratigos
Hello! I need to update a dynamically built query such that items with photos order before items without photos. A Photo belongs to an Item.
What I would do in SQL is left join on the association table (“photos”), select a named count via COUNT(photos.id) AS photos_count, and then either order by it directly, or order by a case statement where photos_count > 0 (or IS NOT NULL …).
I am having a very difficult time expressing this with Ecto. I need to define this in a small helper function that is piped into an existing list of query building functions, so I dont have much control over how tables are aliased. Furthermore, all of my efforts to define a named COUNT result in an error like:
undefined function escape_count/0
Ive tried via: query |> select_merge([item, ..., photo], %{photos_count: count(photo.id)}
Or: `query |> select_merge([item, …, photo], fragment(“COUNT(?) AS photos_count”, photo.id))
Or (guessing here) select_merge([item, ..., photo], %{has_photos: fragment("1 CASE (?) IS NULL THEN 0 ELSE 1", photo.id)})
I couldnt find a way of doing this directly in the order_by clause, though that feels unintuitive anyway.
I would just do this in raw SQL, but being part of a dynamically built query, I cant control the table names and such. I also cant do an in-memory sort with elixir code, since other parts of the query control pagination, etc.
How can I append to an existing query, some clauses that will allow me to order by the presence of associations?
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #hex
- #security











Showing Posts 1 to 6- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
peerreynders
Not sure if this will help in your particular situation but starting simply with this raw SQL:
which can be expressed in keywords form as
or in expression form as
Whether or not you can successfully compose such a query in your particular situation depends entirely on the details …
stratigos
Thanks for the reply. I am very clear on how to do this in raw SQL, and I am familiar with the keyword based approach. Ill see if there is a way I can perhaps merge a new keyword query into an existing Ecto query.
What I cant seem to figure out is:
COUNT(id) AS some_count)There may simply be no such functionality with Ecto, and I may need to approach this by building an entirely new query and merging it into a dynamically built query.
peerreynders
The standard approach, even in SQL, is to simply repeat the
COUNTexpression in theORDER BYas I have already shown:The RDBMS engine is supposed to correlate that expression to the one in the
SELECTlist without evaluating it twice - so there should be no need to alias the column.Adding the
GROUP BYis the real trick - but it may not be possible to adapt your existing query to tolerating theGROUP BY.stratigos
Yes I had just arrived at this realization, and was about to update the thread accordingly -
I was missing the bigger problem by assuming the “aggregate column” had to be named so that it could be matched by the query builder. While this did uncover an additional problem (discussed in my original post), I dont need to do this at all, as you demonstrated.
The real problem is handling the
GROUP BYclause, which, given that this is a dynamically built query, might not be possible. At least, Id have to make this function, which produces the query fragment in question, aware of every column selected by the time it is reached.[edit]
I suppose I dont have the required permission/role for editing a thread or thread title after a certain time period.
More accurately, this thread is about “Order by Association Count within a Dynamically Built Query in Phoenix / Ecto”, and the core of the problem is with forming the
GROUP BYclause whenCOUNTis used inORDER BY.peerreynders
In the simplest case it is possible as Ecto queries are composable. Example:
In your case, the manner in which you are composing the query may be getting in the way at this point. So you may have to restructure your query composition flow to somehow make the
GROUP BYfit when it is needed.stratigos
Yeap, I think you are correct. The problem is not with Ecto lacking any such functionality, but rather a problem any ORM exhibits when dynamically building queries. Looks like the system in which my problem case is exhibited needs redesigned - this is simply the first aggregate query introduced, and thus the first time its showing its limitation.
Refactoring seems to be the answer, plus I may need to upgrade Ecto to get newer features to name/alias JOIN statements (so I can later reference each table in a GROUP BY).