[英]How to query for empty array in jsonb PostgreSQL using Elixir / Ecto
我有一个定义为embeds_many的Ecto模式:
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的参考,但是我不确定如何执行此操作。
您可以尝试使用fragment / 1将原始SQL插入查询中。
在这种情况下,
(from r in Round, where: fragment("? = '{}'", r.growth_cycles)) |> Repo.all
应该管用
从文档中:
无法使用Ecto的查询语法表示所有可能的数据库查询。 需要时,可以使用片段将任何表达式发送到数据库:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.