使用片段的 Ecto“left IN right”查询

2024-03-06

我想使用 postgres IN 运算符(使用 Ecto 库)查询 jsonb 字段

此代码使用简单的 = 运算符:

from a in query, where: fragment("?->>'format' = ?", a.properties, "foo")

但我无法做出任何这些尝试:

from a in query, where: fragment("?->>'format' IN ?", a.properties, ["foo", "bar"])
from a in query, where: fragment("?->>'format' IN (?)", a.properties, ["foo", "bar"])
from a in query, where: fragment("?->>'format' IN ?", a.properties, "('foo', 'bar')"])

任何想法?


除了帕特里克的出色回应之外,请记住,您也可以仅将查询的一部分放入片段中。例如,您可以将其重写为:

from a in query, where: fragment("?->>'format', a.properties) in ["foo", "bar"]

如果将片段放入宏中,甚至可以获得可读的语法:

defmacro jsonb_get(left, right) do
  quote do
    fragment("?->>?", unquote(left), unquote(right))
  end
end

And now:

from a in query, where: jsonb_get(a.properties, "format") in ["foo", "bar"]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用片段的 Ecto“left IN right”查询 的相关文章

随机推荐