sql - Ecto 的片段编译错误

标签 sql postgresql elixir ecto

我正在尝试使用 Ecto 的片段将搜索我的 Postgres JSON 列的行为系统化。

因此,假设我在 profile 列中有以下对象

{
  "first_name": "Margarita",
  "last_name": "Fernandez",
  "rut": "17.754.041-2"
}

我正在尝试做类似的事情

from(u in Users.User, where: fragment("?->>'first_name' LIKE ?", u.profile, ^("%" <> "Marga" <> "%"))) |> Users.Repo.all

但是在函数中

def search(field, value) do
    from(u in Users.User, where: fragment("?->>'#{field}' LIKE ?", u.profile, ^("%" <> value <> "%"))) |> Repo.all
end

但是我得到以下错误

** (Ecto.Query.CompileError) fragment(...) expects the first argument to be a string for SQL fragments, a keyword list, or an interpolated value, got: `"?->>'#{field}' LIKE ?"`

我试图逃避它,插值到以前的变量中,但我做错了什么。

有什么提示吗?

最佳答案

你不能用 fragment 那样做字符串插值.在这种特殊情况下,您可以通过输入 ? 来解决此问题在 ->> 之后并放置 ^fieldfragment参数:

fragment("?->>? LIKE ?", u.profile, ^field, ^("%" <> value <> "%"))

关于sql - Ecto 的片段编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48648297/

相关文章:

elixir phoenix pubsub 通配符主题

php while 循环内的 while 循环

java - Java Web 应用程序的性能测试

sql - 从 SQL Server Polybase 访问 Azure Data Lake Analytics 表

sql - 如果数据存在,则根据 SQL 中给定的优先级返回行

sql - 如何插入一行并附加行号以强制执行唯一性?

postgresql - CREATE SCHEMA IF NOT EXISTS 引发重复键错误

Elixir:更新 map 列表

php - 数据库中的空值

testing - 在 elixir 中定义一个常量模块