Elixir 如何在where子句中的EXTO查询中使用变量
我有一张地图:Elixir 如何在where子句中的EXTO查询中使用变量,elixir,ecto,phoenix,Elixir,Ecto,Phoenix,我有一张地图: allowed_lookup = %{coordinate: "15.0", id: 1} 我想使用这个映射进行一个EXTO查询,以过滤掉数据库中的一些条目 我是这样想的: Enum.reduce(allowed_lookup, Project.Models.Grid, fn {x,y}, query -> IO.puts "#{inspect x} , #{inspect y}"
allowed_lookup = %{coordinate: "15.0", id: 1}
我想使用这个映射进行一个EXTO查询,以过滤掉数据库中的一些条目
我是这样想的:
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)
因此,它将递归地应用map中存在的所有过滤器以获得查询集。
但此代码无效,因为q.x未转换为q.coordinate或q.id 试试这个
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)
exto.Query.where
接受一个关键字列表,其中作为键的字段将与给定值进行比较。在这种情况下,为关键字列表使用简单的[key:value]
构造将不起作用,因为字段和值是动态的。然而,关键字列表也可以动态地构造为元组列表,如[{key,value}]
iex> [{:a, 1}] == [a: 1] # true