Elixir Ecto - PostgreSQL jsonb 函数

3

我将一个基于Ruby on Rails的API转换为Elixir和Phoenix。在我的Postgres数据库中,我有一个带有jsonb列类型的表。其中一个键是颜色数组。例如:

{"id": 12312312, "colors": ["Red", "Blue", "White"]}

我想在Ecto中查询包含颜色Red或Blue的所有记录。本质上,重新创建此查询:
select * from mytable where data->'colors' ?| array['Red', 'Blue']

我在使用Ecto构建查询时遇到了一些困难。以下是我的代码:

注意:“value”将是一个用管道符分隔的颜色列表

  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"]'
1个回答

5
我已经找到了解决我的问题的方法。
def with_colors(query, value) do
  colors = value 
    |> String.split("|")

  from c in query,
  where: fragment("data->'colors' \\?| ?", ^colors))
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接