Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto: Order preloaded data in collection with has_many association

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.

like image 506
nitomoe Avatar asked Apr 10 '17 18:04

nitomoe


1 Answers

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)

like image 150
Harrison Lucas Avatar answered Nov 02 '22 17:11

Harrison Lucas