Elixir-Exto-PostgreSQL jsonb函数
我正在将RubyonRails API转换为Elixir和Phoenix。在我的Postgres数据库中,我有一个jsonb列类型的表。json中的一个键是颜色数组。例如:Elixir-Exto-PostgreSQL jsonb函数,postgresql,elixir,phoenix-framework,ecto,Postgresql,Elixir,Phoenix Framework,Ecto,我正在将RubyonRails API转换为Elixir和Phoenix。在我的Postgres数据库中,我有一个jsonb列类型的表。json中的一个键是颜色数组。例如: {"id": 12312312, "colors": ["Red", "Blue", "White"]} 我试图从Ecto查询我的表中所有包含红色或蓝色的记录。基本上,重新创建此查询: select * from mytable where data->'colors' ?| array['Red', 'Blue']
{"id": 12312312, "colors": ["Red", "Blue", "White"]}
我试图从Ecto查询我的表中所有包含红色或蓝色的记录。基本上,重新创建此查询:
select * from mytable where data->'colors' ?| array['Red', 'Blue']
select * from mytable where data->'colors' @> '["Red", "Blue"]'
我在用EXTO构造这个查询时遇到了一些困难。以下是我所拥有的:
注意:“值”将是以管道分隔的颜色列表
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' ?| array['Red', 'Blue']
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