簡體   English   中英

如何使用Elixir / Ecto在jsonb PostgreSQL中查詢空數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM