简体   繁体   English

在查询表达式中带有动态字段名称的通用可组合Ecto查询

[英]Generic composable Ecto query w/ dynamic field name in query expression

I'm trying to allow for passing in a field name and running it in an Ecto query expression dynamically, like so: 我试图允许传入一个字段名称,并在Ecto查询表达式中动态运行它,如下所示:

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? 有什么办法可以做到这一点?

You need to use field/2 to dynamically generate fields in queries: 您需要使用field / 2在查询中动态生成字段:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM