【问题标题】:Elixir Ecto query - preserving order of outputElixir Ecto 查询 - 保留输出顺序
【发布时间】:2020-01-20 15:29:11
【问题描述】:

我有一个ID列表["123", "321", "101"]

还有一个查询segments = Repo.all(from(s in Segment, where: s.id in ^ids))

我的匹配段的输出与列表中的顺序不同。例如。如果这是Enum.map,那么订单将被保留。有没有一种方法可以做到这一点,只使用一个查询,而不必执行Enum.each 之类的操作?

【问题讨论】:

标签: elixir ecto


【解决方案1】:

这是我将one of the answers from @zwippie's comment 转换为 Ecto(用于 Postgres)的尝试:

defmodule Segment do
  ...

  def by_id_in_order(query, ids) do
    query
    |> join(:inner, [s], o in fragment("SELECT * FROM UNNEST(?::int[]) WITH ORDINALITY AS o (id, ordinal)", ^ids), on: s.id == o.id)
    |> order_by([s, o], asc: o.ordinal)
  end
end

像这样使用

Segment
|> Segment.by_id_in_order([123, 321, 101])
|> Repo.all()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多