【发布时间】:2021-01-04 23:52:08
【问题描述】:
假设我有一个 jsonb 字段,我想根据其中一个字段对其进行排序,它也应该使用动态,因为在编译时无法告诉字段名称。我目前拥有的是:
def order_by_dynamic([sort_direction, %{binding_name: binding_name, json_field: json_key, field: field}]) do
[{sort_direction |> String.to_atom(), dynamic([{^binding_name, c}], create_fragment([{c.details, ^field}, json_key]))}]
end
defmacro create_fragment(fields) do
require Ecto.Query
query = "?->>?"
quote do
fragment(unquote(query), unquote_splicing(fields))
end
end
这段代码的问题是它无法编译:
** (Ecto.Query.CompileError) Tuples can only be used in comparisons with literal tuples of the same size
expanding macro: Ecto.Query.dynamic/2
我也尝试在将json字段名称插入到字符串中,然后再将其传递给片段,错误是:
** (Ecto.Query.CompileError) to prevent SQL injection attacks, fragment(...) does not allow strings to be interpolated as the first argument via the `^` operator, got: `"?->>#{json_key}"`
expanding macro: Ecto.Query.dynamic/2
我是否遗漏了什么,或者当前的片段宏无法实现?
【问题讨论】:
-
您应该在引用之前插入
"?->>?"的左侧参数。有点像这里:stackoverflow.com/a/39696235/2035262你能提供一个 MCVE 吗?