postgresql - Elixir Ecto - PostgreSQL jsonb 函数

标签 postgresql elixir phoenix-framework ecto

我正在将 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/

相关文章:

java - 如何使用复合类型数组调用 postgres 函数

java - 如果我们使用@OneToMany注释,我们是否必须在数据库中本地定义一对多关系

elixir - :dets. open_file 参数错误

phoenix-framework - 在 Phoenix 框架中压缩 JSON 响应

elixir - 无法转换为类型 :naive_datetime in query

ruby-on-rails - 按 ID 分组并对行求和的 ActiveRecord 查询

bash - Sed 命令不识别撇号

混合键 Elixir map

Elixir:将位列表转换为二进制

elixir - 验证一个日期比另一个日期晚或相同