【问题标题】:Elixir Ecto - PostgreSQL jsonb FunctionsElixir Ecto - PostgreSQL jsonb 函数
【发布时间】:2016-09-02 00:24:54
【问题描述】:

我正在将 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"]'

【问题讨论】:

    标签: postgresql elixir phoenix-framework ecto


    【解决方案1】:

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

    def with_colors(query, value) do
      colors = value 
        |> String.split("|")
    
      from c in query,
      where: fragment("data->'colors' \\?| ?", ^colors))
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 2016-10-26
      • 1970-01-01
      • 2017-01-12
      相关资源
      最近更新 更多