如何使用 Elixir / Ecto 在 jsonb PostgreSQL 中查询空数组

How to query for empty array in jsonb PostgreSQL using Elixir / Ecto

我有一个 Ecto 模式 embeds_many 定义如下:

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

这转换为 PostgreSQL 中的 jsonb 字段。默认值为空数组 - []。我想写一个 Ecto 查询,returns 只有 growth_cycles = [] 的回合(growth_cycles 不是 set/empty)。

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

    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 的参考资料,但我不确定如何执行此操作。

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

在这种情况下,类似于

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

应该可以

来自文档:

It is not possible to represent all possible database queries using Ecto's query syntax. When such is required, it is possible to use fragments to send any expression to the database: