Phoenix:订购查询集 [英] Phoenix: Ordering a query set
问题描述
我(一个菜鸟)在玩Phoenix框架,玩得开心,并建立了一个很小的twitter克隆.我一切正常,但是,我想按updated_at
字段(升序)排序推文.从tweet_controller可以看到,我试图弄乱order_by子句,但这对我没有任何帮助.
I'm [a noob] playing around with the Phoenix framework for fun and building a small twitter clone. I everything working, however, I want to order the tweets by the updated_at
field (ascending). As you can see from tweet_controller, I have tried messing around with an order_by clause, but this did nothing for me.
问题
我该如何实现?在EEx内还是在tweet_controller本身内?
How do I achieve this? Within the EEx or within the tweet_controller itself?
tweet/index.html.eex
<div class="row">
<%= for tweet <- @tweets do %>
<h4><%= tweet.tweet %></h4>
<% end %>
</div>
controllers/tweet_controller.ex
...
alias TodoApp.Tweet
def index(conn, _params) do
tweets = Repo.all(Tweet, order_by: tweet)
render(conn, "index.html", tweets: tweets)
end
...
推荐答案
您需要使用 Ecto查询:
query = from(t in Tweet, order_by: t.updated_at)
tweets = Repo.all(query)
您可能要考虑在Tweet模型中为查询定义一个函数.
You may want to consider defining a function in your Tweet model for the query.
def ordered(query) do
from t in query,
order_by: t.updated_at
end
您还可以使用函数语法:
You can also use the function syntax:
def ordered(query) do
query
|> order_by([t], t.updated_at)
end
然后您可以在控制器中使用它:
Then you can use this in your controller:
tweets = Tweet |> Tweet.ordered() |> Repo.all()
以下是有关查询的好帖子: http://blog.drewolson.org/composable -queries-ecto/
Here is a good post on queries: http://blog.drewolson.org/composable-queries-ecto/
这篇关于Phoenix:订购查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!