Order_by不适用于动态查询

时间:2020-04-09 11:17:37

标签: elixir ecto phoenix

我想按照here中的示例在动态查询中使用order_by

def filter(params) do
  Post
  |> order_by(^filter_order_by(params["order_by"]))
end

def filter_order_by("published_at_desc"),
  do: dynamic([p], desc: p.published_at)

但是我得到的是:

** (Ecto.Query.CompileError) Tuples can only be used in comparisons with literal tuples of the same size
    (ecto 3.1.7) expanding macro: Ecto.Query.dynamic/2
    (elixir 1.10.0-rc.0) lib/kernel/parallel_compiler.ex:233: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/7

他们的示例中还有第二种变体:

def filter_order_by("published_at_desc"),
  do: [desc: dynamic([p], p.published_at)]

这不会在编译时引发错误,而是在运行时:

** (exit) an exception was raised:
    ** (ArgumentError) expected a field as an atom, a list or keyword list in `order_by`, got: `dynamic([c], c.inserted_at)`
        (ecto 3.1.7) lib/ecto/query/builder/order_by.ex:105: Ecto.Query.Builder.OrderBy.field!/2
        (ecto 3.1.7) lib/ecto/query/builder/order_by.ex:115: anonymous fn/2 in Ecto.Query.Builder.OrderBy.order_by!/2
        (elixir 1.10.0-rc.0) lib/enum.ex:1396: Enum."-map/2-lists^map/1-0-"/2

0 个答案:

没有答案