【问题标题】:Phoenix: Ordering a query setPhoenix:订购查询集
【发布时间】:2015-11-19 22:09:23
【问题描述】:

我是 [菜鸟] 玩弄 Phoenix 框架并构建一个小型 Twitter 克隆的乐趣。我一切正常,但是,我想按updated_at 字段(升序)对推文进行排序。正如您从 tweet_controller 中看到的那样,我尝试过使用 order_by 子句,但这对我没有任何作用。

问题

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

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
...

【问题讨论】:

    标签: elixir phoenix-framework ecto


    【解决方案1】:

    您需要使用Ecto Query

    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/

    【讨论】:

    • 只是为了确认,这不能用 EEx 完成吗?
    • @plotplot 这是属于数据库的东西(因为数据库会在查询执行之前排序,这对分页很重要。)即使您确实想使用Enum.sort 进行排序我会在控制器而不是模板中执行那种事情。
    猜你喜欢
    • 1970-01-01
    • 2013-01-12
    • 2023-03-10
    • 2012-01-18
    • 2020-08-30
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    相关资源
    最近更新 更多