mmport80

mmport80

Sort Ecto Query Results Ordered by Nested Association

I have a query like:

Alarms 
|> preload(:event) 
|> order_by([{:desc, :event[:id]}]) 
|> Repo.all()

You can see what I am trying to do, reach into the preloaded event and order the alarms by the id field within the event field / association.

I feel I am very close to achieving this, but I also suspect that it is not possible, and I need to use a join.

Any advice?

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Ah. You can tweak what you have a little I think and do:

Alarms
|> join(:left, [a], e in assoc(a, :event)) 
|> order_by([a, e], [{:desc, e.id}]) 
|> preload([a, e], event: e)
|> Repo.all()

In any case, doing the join so that you can order seems like exactly the right way to do the SQL.

peerreynders

peerreynders

Order on each respective table to get a total order:

   albums_query =
      Album
      |> order_by([m], [desc: m.id])

    Artist
    |> join(:left, [a], m in assoc(a, :albums))
    |> order_by([a,m], [asc: a.id])
    |> preload([a,m], [albums: ^albums_query])
    |> Repo.all()

That being said associations by their nature have to stay clustered together.

peerreynders

peerreynders

Order gets overridden:

|> preload([a,m], :albums)

Order is respected

|> preload([a,m], [albums: m])

At this point I’m not even sure what the second one means … I blame macros as the difference seems a bit subtle (and as it should be unrelated).

Ok - preload/3:

  • [:albums] give me the whole bag unconstrained by any SQL constraints.
  • [albums: m] just give me those items in the bag that are in compliance with the SQL constraints.

The optional/vanishing list markers aren’t helping clarity either.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Check out preload queries, they’re perfect for this: https://hexdocs.pm/ecto/Ecto.Query.html#preload/3-preload-queries

peerreynders

peerreynders

Not too elegant…
Unsure how I can generalise this, and reuse it…

It’s not exactly clear what kind of “reuse” (or elegance) you are after.

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
polypush135
As many of you may have realized by now (sorry for all the posts here) I’ve been working on a db problem where I’m trying to aggregate a ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement