如何在Ecto查询中插入字段? [英] How do interpolation fields in Ecto queries?
问题描述
Ecto文档显示了如何进行插值.但是我在查询中需要动态字段.我有数十个字段,并且为每个字段编写查询似乎并不连贯.
The Ecto documentation shows how to do interpolation values. But I need dynamic fields in my queries. I have dozens of fields and write queries for each of them does not seem cohesive.
defmodule Hedone.SearchController do
use Hedone.Web, :controller
alias Hedone.User
def idade(conn, %{"idade+" => maior, "idade-" => menor, "campo" => campo}) do
IO.inspect campo
query = from u in User, where: u.campo > ^maior and u.campo < ^menor, select: u.name
pesquisa = Repo.all query
IO.inspect pesquisa
text conn, "Works"
end
end
此控制器生成以下错误:
This controller generates the following error:
** (Ecto.QueryError) web/controllers/search.ex:8: field `Hedone.User.campo` in `where` does not exist in the schema in query:
from u in Hedone.User,
where: u.campo > ^18 and u.campo < ^40,
select: u.name
自动翻译.
推荐答案
我假设 campo
包含一个字符串,其中包含您要使用的字段的名称,例如年龄"
.您可以在其中使用 field
查询此:
I'm assuming campo
contains a string with the name of the field you want to use, e.g. "age"
. You can use field
in the query for this:
def idade(conn, %{"idade+" => maior, "idade-" => menor, "campo" => campo}) do
campo = String.to_existing_atom(campo)
query = from u in User, where: field(u, ^campo) > ^maior and field(u, ^campo) < ^menor, select: u.name
pesquisa = Repo.all query
IO.inspect pesquisa
text conn, "Works"
end
field
期望该字段是一个原子,因此我使用了 String.to_existing_atom
安全地将字符串转换为atom.由于您必须已经在模型的架构中定义了字段,因此 String.to_existing_atom
不会因任何有效的字段名称而失败.
field
expects the field to be an atom, so I've used String.to_existing_atom
to safely convert a string to atom. Since you already must have defined the field in the schema of the model, String.to_existing_atom
will not fail for any valid field name.
这篇关于如何在Ecto查询中插入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!