【问题标题】:How to query for empty array in jsonb PostgreSQL using Elixir / Ecto如何使用 Elixir / Ecto 在 jsonb PostgreSQL 中查询空数组
【发布时间】:2019-04-17 13:53:59
【问题描述】:

我有一个 Ecto 架构,其中 embeds_many 定义如下:

  schema "rounds" do
    embeds_many :growth_cycles, SomeModule.GrowthCycle, on_replace: :delete
  end

这转换为 PostgreSQL 中的 jsonb 字段。默认值为空数组 - []。我想编写一个 Ecto 查询,它只返回具有 growth_cycles = [] 的回合(growth_cycles 未设置/为空)。

我尝试过的最简单的方法是:

    from(r in Round, where: r.growth_cycles == [])

但这会产生以下错误:

** (Postgrex.Error) ERROR 42P18 (indeterminate_datatype) cannot determine type of empty array
...
hint: Explicitly cast to the desired type, for example ARRAY[]::integer[].

我也试过了:

    from(r in Round, where: length(r.growth_cycles) == 0)

但这给出了一个错误,指出长度不是有效的查询表达式。

我看到有关使用片段下拉到原始 PostgreSQL 的引用,但我不确定如何执行此操作。

【问题讨论】:

    标签: postgresql elixir ecto


    【解决方案1】:

    您可以尝试使用fragment/1 将原始 SQL 插入到您的查询中。

    在这种情况下,类似于

    (from r in Round, where: fragment("? = '{}'", r.growth_cycles)) |> Repo.all
    

    应该工作

    来自文档:

    使用 Ecto 的查询语法表示所有可能的数据库查询是不可能的。如果需要,可以使用片段将任何表达式发送到数据库:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多