我正在尝试使用 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
那样做字符串插值.在这种特殊情况下,您可以通过输入 ?
来解决此问题在 ->>
之后并放置 ^field
在fragment
参数:
fragment("?->>? LIKE ?", u.profile, ^field, ^("%" <> value <> "%"))
关于sql - Ecto 的片段编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48648297/