Ecto: order pre-loaded data into collections using has_many association

Say I have this for retrieving all threads:

Thread |> Thread.ordered |> Repo.all |> Repo.preload([:posts])

How can I provide an order_by clause for :posts? I cannot find anything in the documentation that refers to Ecto.Repo.preload/1, so none of the above examples is useful for figuring out how to use this syntax correctly.

+4
source share
1 answer

The Ecto.Query module also makes it easy to apply certain queries to things, such as preloading.

, , - , .

, :

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)])

( , )

+6

Source: https://habr.com/ru/post/1674506/


All Articles