Elixir Ecto - PostgreSQL jsonb 函数

Elixir Ecto - PostgreSQL jsonb Functions

我正在将 Rails API 上的 Ruby 转换为 Elixir 和 Phoenix。在我的 Postgres 数据库中,我有一个 table 和 jsonb 列类型。 json 中的一个键是一组颜色。例如:

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

我想从 Ecto 做的是查询我的 table 包含红色或蓝色的所有记录。本质上,重新创建此查询:

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"]'

我找到了解决问题的方法。

def with_colors(query, value) do
  colors = value 
    |> String.split("|")

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