我正在将 Ruby on Rails API 转换为 Elixir 和 Phoenix。在我的 Postgres 数据库中,我有一个包含 jsonb 列类型的表。 json 中的一个键是一组颜色。例如:
{"id": 12312312, "colors": ["Red", "Blue", "White"]}
我想从 Ecto 做的是在我的表中查询包含红色或蓝色的所有记录。本质上,重新创建此查询:
select * from mytable where data->'colors' ?| array['Red', 'Blue']
我在使用 Ecto 构建此查询时遇到了一些困难。这是我所拥有的:
注意:“值”将是一个竖线分隔的颜色列表
def with_colors(query, value) do
colors = value
|> String.split("|")
|> Enum.map(fn(x) -> "'#{x}'" end)
|> Enum.join(", ")
# colors should look like "'Red', 'Blue'"
from c in query,
where: fragment("data->'colors' \\?| array[?]", ^colors))
end
这目前没有按预期工作。我对替换问号有疑问,因为它似乎在我的字段周围包含了额外的引号。使用片段的正确方法是什么?或者有更好的方法吗?
我将再次遇到这个问题,因为我还必须重新创建这个查询:
select * from mytable where data->'colors' @> '["Red", "Blue"]'
最佳答案
我找到了解决问题的方法。
def with_colors(query, value) do
colors = value
|> String.split("|")
from c in query,
where: fragment("data->'colors' \\?| ?", ^colors))
end
关于postgresql - Elixir Ecto - PostgreSQL jsonb 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39282667/