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

后端 未结 1 1471
生来不讨喜
生来不讨喜 2021-01-04 05:29

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          


        
相关标签:
1条回答
  • 2021-01-04 06:21

    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)
    
    0 讨论(0)
提交回复
热议问题