Let's say I have this for fetching all threads:
Thread |> Thread.ordered |> Repo.all |> Repo.preload([:posts])
How could I provide an order_by clause for :posts
? I can't seem to locate anything in the documentation that references Ecto.Repo.preload/1
, so none of the provided examples appear helpful for figuring out how to use this syntax properly.
The Ecto.Query module makes it really easy to also apply certain queries to things like preloading.
The way we achieve this is by passing a query into the preload function, which then restricts the results of the preload to that query.
For example, in your case:
import Ecto.Query # => Needed to use the ecto query helpers
Thread
|> Thread.ordered
|> Repo.all
|> Repo.preload([posts: (from p in Post, order_by: p.published_at)])
(assuming you have a published at field on the posts)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With