Generic composable Ecto query w/ dynamic field name in query expression

纵饮孤独 提交于 2019-12-01 15:24:58

问题


I'm trying to allow for passing in a field name and running it in an Ecto query expression dynamically, like so:

def count_distinct(query, field_name) when is_binary(field_name) do
  query
  |> select([x], count(Map.fetch!(x, field_name), :distinct))
end

However, I get this compilation error:

(Ecto.Query.CompileError) `Map.fetch!(x, field_name)` is not a valid query expression

Is there any way to accomplish this?


回答1:


You need to use field/2 to dynamically generate fields in queries:

query
|> select([x], count(field(x, ^field_name), :distinct))

An example using the other query syntax for completion:

from x in query,
  select: count(field(x, ^field_name), :distinct)


来源:https://stackoverflow.com/questions/34641659/generic-composable-ecto-query-w-dynamic-field-name-in-query-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!