我正在尝试构建一个函数,用于在查询中的给定表的字段中搜索术语。
对于像这样的查询
initial_query =
Answer
|> join(:left, [a], q in assoc(a, :question), as: :question)
|> join(:left, [a, q], s in assoc(a, :survey), as: :survey)
Run Code Online (Sandbox Code Playgroud)
我希望能够通过引用的表中进行搜索:question和:survey。
现在,此代码有效:
initial_query
|> or_where(
[question: t], #:question hard coded
fragment(
"CAST(? AS varchar) ILIKE ?",
field(t, ^field),
^"%#{search_term}%"
)
)
Run Code Online (Sandbox Code Playgroud)
但是,我想要一个将命名绑定作为参数的函数,但我找不到方法来做到这一点。
我的尝试:
defp search_field(initial_query, table, field, search_term) do
initial_query
|> or_where(
[{table, t}],
fragment(
"CAST(? AS varchar) ILIKE ?",
field(t, ^field),
^"%#{search_term}%"
)
)
end
Run Code Online (Sandbox Code Playgroud)
给出错误
** (Ecto.Query.CompileError) unbound variable
t …