我[一个菜鸟]为了好玩而玩弄 Phoenix 框架并构建一个小型 Twitter 克隆。我一切正常,但是,我想按updated_at
字段(升序)。正如您从 tweet_controller 中看到的,我尝试过使用 order_by 子句,但这对我没有任何作用。
Question
我该如何实现这一目标?在 EEx 内还是 tweet_controller 本身内?
推文/index.html.eex
<div class="row">
<%= for tweet <- @tweets do %>
<h4><%= tweet.tweet %></h4>
<% end %>
</div>
控制器/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
...
你需要使用一个外链查询 http://hexdocs.pm/ecto/Ecto.Query.html:
query = from(t in Tweet, order_by: t.updated_at)
tweets = Repo.all(query)
您可能需要考虑在 Tweet 模型中为查询定义一个函数。
def ordered(query) do
from t in query,
order_by: t.updated_at
end
您还可以使用函数语法:
def ordered(query) do
query
|> order_by([t], t.updated_at)
end
然后你可以在你的控制器中使用它:
tweets = Tweet |> Tweet.ordered() |> Repo.all()
这是一篇关于查询的好帖子:http://blog.drewolson.org/composable-queries-ecto/ http://blog.drewolson.org/composable-queries-ecto/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)