makeitrein
Happy Friday, would love to query the elixir forum hive mind to get some help on an ecto problem that’s been bothering me today…
I have the following base query for my Fic model…
def summary_query(query) do
from f in query,
left_join: r in assoc(f, :reviews),
group_by: f.id,
preload: [
:submitter,
:genres,
reviews: :submitter,
],
select: %{
f |
review_count: fragment("count(?) as review_count", r.id),
review_avg: fragment("coalesce(?::float, 0) as review_avg", avg(r.rating))
}
end
I’d like to compose my summary query with some sorting and filtering queries. These sorting and filtering queries need to use the computed review_count and review_avg columns…
Example: Fic |> summary_query |> at_least_ten_reviews_query
Unfortunately, when I try to do either this…
from f in query, where: f.review_avg > 10
Or…
from f in query, where: fragment("review_avg") > 10
I get errors, either saying that “field review_avg in where is a virtual field in schema Ficdb.Fanfics.Fanfic in query:” or “column “review_avg” does not exist”
What’s the correct syntax for working with these virtual/aggregate columns? Thx!
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming











Showing Posts 1 to 3- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
amarraja
It’s more a SQL thing than Ecto, but to filter by aggregate fields you need to use “having”, not “where”
makeitrein
Thx! Good catch
tfwright
I had a similar problem, and the cause was that I needed to ensure the alias was being added in a subquery, not a composed query: