-->

Ecto: Order preloaded data in collection with has_

2020-03-02 02:38发布

问题:

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.

回答1:

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)