ecto:使用has_many关联对集合中的预加载数据进行排序 [英] Ecto: Order preloaded data in collection with has_many association

查看:64
本文介绍了ecto:使用has_many关联对集合中的预加载数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个用于获取所有线程:

Let's say I have this for fetching all threads:

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

如何为:posts提供order_by子句?我似乎在引用Ecto.Repo.preload/1的文档中找不到任何内容,因此提供的所有示例似乎都无助于弄清楚如何正确使用此语法.

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.

推荐答案

Ecto.Query 模块使将某些查询应用于预加载等操作变得非常容易.

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.

例如,在您的情况下:

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)

这篇关于ecto:使用has_many关联对集合中的预加载数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆