我有一个带有embeds_many的Ecto架构,如下所示:
schema "rounds" do
embeds_many :growth_cycles, SomeModule.GrowthCycle, on_replace: :delete
end
这转换为PostgreSQL中的jsonb字段。默认值为空数组 - []。我想编写一个Ecto查询,只返回具有growth_cycles = []的round(grow_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的查询语法无法表示所有可能的数据库查询。如果需要,可以使用片段将任何表达式发送到数据库: