【问题标题】:How to pass values in JSON for the Ecto Query?如何在 JSON 中为 Ecto 查询传递值?
【发布时间】:2017-01-23 15:06:42
【问题描述】:

客户端发送以下 JSON:{"user": {"age+":18,"age-":40}}

在我的控制器中,我有以下内容:

def procura(conn, query) do
  maior = conn.params["user"]["age+"]
  menor = conn.params["user"]["age-"]
 query = from u in query, where: u.age > ^maior and u.age < ^menor, select: u.name
  pesquisa = Repo.all query
  IO.puts pesquisa
end

但我收到了编译器警告:** (Protocol.UndefinedError) protocol Ecto.Queryable not implemented for %{}

如何为 Ecto 查询传递 JSON 中的值?

我的目标是基于 JSON 字段进行查询。我想查询年龄在 x 到 y 之间的用户。 自动翻译。

【问题讨论】:

  • 查询的价值是什么?您似乎将 %{} 作为第二个参数传递给 procura 而不是查询。此外,您需要将from 行更改为query = from u in query, ...
  • procura 是动作吗?如果是,则查询将从请求中清除参数。请在 show 上尝试查询 IO.inspect 作为结果。应该是地图。如果它是一个动作,你应该返回一个连接。
  • 您好!我的目标是基于 JSON 字段进行搜索。我想搜索年龄在 x 到 y 之间的用户。我没有得到。

标签: json elixir phoenix-framework ecto


【解决方案1】:

你可能想做的是:

在我的控制器中,我有以下内容:

def procura(conn, %{"user" => %{ "idade+" => maior, "idade-" => menor }}) do
  query = from u in Module.Model, where: u.idade > ^maior and u.idade < ^menor, select: u.name
  pesquisa = Repo.all query
  IO.puts pesquisa
  text conn, "Works"
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    相关资源
    最近更新 更多