2017-04-03 87 views
0

我是新來菲尼克斯(在Ruby/Rails的到來),並在文檔周圍挖掘後,我無法弄清楚如何外生代表這個相對簡單的SQL查詢:如何在Ecto中將其他表格分組並排序?

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) 

我錯過了什麼?公認的答案後,工作


編輯:

如果返回的數量,你會打破預壓。今天早上我弄了一會兒。預加載似乎只在它只是結構列表時才起作用。

下面是做了什麼,我想,基於上面的查詢最終代碼(與您的應用程序替換應用程序。):

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) 

回答

1

下應該做的工作,但請注意,我的天堂」噸測試這個:

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)} 
+0

請參閱我的筆記在我的編輯問題,特別是關於選擇語句和預加載。 –

相關問題