如何在 Ecto 中拉取由另一个 table 分组和排序的项目?
How to pull items grouped and sorted by another table in Ecto?
我是 Phoenix 的新手(来自 Ruby/Rails),在查阅了文档之后,我不知道如何在 Ecto 中表示这个相对简单的 SQL 查询:
select d.*, t.doc_id, count(*) as cnt
from taggings t, docs d
where d.id = t.doc_id
group by d.id, t.doc_id
order by cnt desc
limit 20;
这就是下一行,我要发送到模板的内容:
top_docs = Repo.all(top_docs_query) |> Repo.preload(:tags) |> Repo.preload(:taggings)
我错过了什么?
使用接受的答案后编辑:
如果你 return 计数,你将中断预加载。 今天早上这把我搞砸了一段时间。预加载似乎只有在它只是一个结构列表时才有效。
根据上面的查询(用您的应用程序替换 App..),这是完成我想要的最终代码:
top_docs_query =
from d in App.Doc,
join: t in App.Tagging, on: [doc_id: d.id],
group_by: [d.id, t.doc_id],
order_by: [desc: count(t.id)],
limit: 20
# select: {d, t.doc_id, count(d.id)} <- This is what was breaking the preloading.
top_docs = Repo.all(top_docs_query) |> Repo.preload(:taggings) |> Repo.preload(:tags)
下面应该可以完成这项工作,但请注意我还没有测试过这个:
from t in Tagging,
join: d in Doc, on: [id: t.doc_id],
group_by: [d.id, t.doc_id],
order_by: [desc: count(d.id)],
limit: 20,
select: {d, t.doc_id, count(d.id)}
我是 Phoenix 的新手(来自 Ruby/Rails),在查阅了文档之后,我不知道如何在 Ecto 中表示这个相对简单的 SQL 查询:
select d.*, t.doc_id, count(*) as cnt
from taggings t, docs d
where d.id = t.doc_id
group by d.id, t.doc_id
order by cnt desc
limit 20;
这就是下一行,我要发送到模板的内容:
top_docs = Repo.all(top_docs_query) |> Repo.preload(:tags) |> Repo.preload(:taggings)
我错过了什么?
使用接受的答案后编辑:
如果你 return 计数,你将中断预加载。 今天早上这把我搞砸了一段时间。预加载似乎只有在它只是一个结构列表时才有效。
根据上面的查询(用您的应用程序替换 App..),这是完成我想要的最终代码:
top_docs_query =
from d in App.Doc,
join: t in App.Tagging, on: [doc_id: d.id],
group_by: [d.id, t.doc_id],
order_by: [desc: count(t.id)],
limit: 20
# select: {d, t.doc_id, count(d.id)} <- This is what was breaking the preloading.
top_docs = Repo.all(top_docs_query) |> Repo.preload(:taggings) |> Repo.preload(:tags)
下面应该可以完成这项工作,但请注意我还没有测试过这个:
from t in Tagging,
join: d in Doc, on: [id: t.doc_id],
group_by: [d.id, t.doc_id],
order_by: [desc: count(d.id)],
limit: 20,
select: {d, t.doc_id, count(d.id)}