Ecto: Order preloaded data in collection with has_many association

非 Y 不嫁゛ 提交于 2019-11-30 04:57:03

问题


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)



来源:https://stackoverflow.com/questions/43330145/ecto-order-preloaded-data-in-collection-with-has-many-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!