【问题标题】:How to use variables in in a Ecto query in where clause如何在 where 子句的 Ecto 查询中使用变量
【发布时间】:2018-09-30 22:30:30
【问题描述】:

我有一张地图:

  allowed_lookup = %{coordinate: "15.0", id: 1}

我想用这个映射来做一个 Ecto 查询来过滤掉数据库中的一些条目。

我在想这样的事情:

Enum.reduce(allowed_lookup, Project.Models.Grid,
            fn {x,y}, query ->
                IO.puts "#{inspect x} , #{inspect y}"
                query = where(query, [q] , q.x == ^y)
            end)

queryset = Project.Repo.all(query)

所以它将递归地应用地图中存在的所有过滤器来获取查询集。 但是此代码无效,因为 q.x 未转换为 q.coordinate 或 q.id 。

【问题讨论】:

    标签: elixir ecto phoenix


    【解决方案1】:

    试试这个

    allowed_lookup = %{coordinate: "15.0", id: 1}
    Enum.reduce(allowed_lookup, Project.Models.Grid,
            fn {x,y}, query ->
                IO.puts "#{inspect x} , #{inspect y}"
    
                field_query = [{x, y}] #dynamic keyword list
    
                query|>where(^field_query)
            end)
    
    queryset = Project.Repo.all(query)
    

    Ecto.Query.where 接受一个关键字列表,其中作为键给出的字段将与给定值进行比较。在这种情况下,使用简单的[key: value] 构造关键字列表将不起作用,因为字段和值是动态的。但是,关键字列表也可以动态地构建为像[{key, value}] 这样的元组列表。

     iex> [{:a, 1}] == [a: 1] # true
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 2017-01-05
      • 1970-01-01
      • 2015-11-11
      相关资源
      最近更新 更多