凤凰城:订购查询集

plo*_*lot 4 elixir ecto phoenix-framework

我是[noob]玩凤凰框架的乐趣和建立一个小的推特克隆.我工作的一切,但是,我想按updated_at字段(升序)订购推文.正如你在tweet_controller中看到的那样,我已经尝试过使用order_by子句,但这对我没有任何帮助.

我该如何实现这一目标?在EEx内或tweet_controller本身内?

鸣叫/ index.html.eex

<div class="row">
  <%= for tweet <- @tweets do %>

  <h4><%= tweet.tweet %></h4>

  <% end %> 
</div>
Run Code Online (Sandbox Code Playgroud)

控制器/ 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
...
Run Code Online (Sandbox Code Playgroud)

Gaz*_*ler 15

您需要使用Ecto查询:

query = from(t in Tweet, order_by: t.updated_at)
tweets = Repo.all(query)
Run Code Online (Sandbox Code Playgroud)

您可能需要考虑在Tweet模型中为查询定义一个函数.

def ordered(query) do
  from t in query,
    order_by: t.updated_at
end
Run Code Online (Sandbox Code Playgroud)

您还可以使用函数语法:

def ordered(query) do
  query
  |> order_by([t], t.updated_at)
end
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的控制器中使用它:

tweets = Tweet |> Tweet.ordered() |> Repo.all()
Run Code Online (Sandbox Code Playgroud)

这是一篇关于查询的好文章:http://blog.drewolson.org/composable-queries-ecto/

  • @plotplot这是属于数据库的东西(因为数据库将在执行查询之前进行排序,这对于分页很重要.)即使你确实想要使用`Enum.sort`排序,我也会执行那种控制器中的东西而不是模板. (2认同)