2017-04-10 66 views
3

订购预装数据比方说,我有这样的用于获取所有线程:外生:在收集与协会的has_many

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

我怎么能为:posts的ORDER_BY条款?我似乎无法找到引用Ecto.Repo.preload/1的文档中的任何内容,因此没有提供的示例对于确定如何正确使用此语法很有帮助。

+1

时退房“预紧查询”部分:https://hexdocs.pm /ecto/Ecto.Query.html#preload/3。它描述了你想要的东西。 – Dogbert

回答

4

Ecto.Query模块可以很容易地将某些查询应用于预加载等事情。

我们通过将查询传递给预加载函数,然后将预加载结果限制为该查询。

例如,你的情况:

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

(假设你有一个在出版领域的职位)在这里

+1

感谢您的帮助,它的工作原理!如果有人发现这个线程并且有相同的问题,我还需要'导入Ecto.Query'。 – nitomoe

+0

@nitomoe好皮卡,生病添加! –

+0

这不起作用了。现在,您需要编写一个查询,然后在将该查询传递给预加载时进行查询,如下所示: 'comments_query = from c in Comment,order_by:c.popularity,limit:5 Repo.all from p in Post ,preload:[评论:^ comments_query]' https://hexdocs.pm/ecto/Ecto.Query.html#preload/3-preload-queries –