我试图允许传入一个字段名称并动态地在一个Ecto查询表达式中运行它,如下所示:
def count_distinct(query, field_name) when is_binary(field_name) do query |> select([x], count(Map.fetch!(x, field_name), :distinct)) end
但是,我收到此编译错误:
(Ecto.Query.CompileError) `Map.fetch!(x, field_name)` is not a valid query expression
有没有办法实现这个目标?
您需要使用field/2在查询中动态生成字段:
query |> select([x], count(field(x, ^field_name), :distinct))
使用其他查询语法完成的示例:
from x in query, select: count(field(x, ^field_name), :distinct)