[英]Rails Scope for JSONB Hash with Array for Value
我正在使用一個 JSONB 列,其中數據存儲為 { key => [value, value, value ] } 如何編寫一個范圍來返回包含特定鍵數組中的特定值的記錄?
我已經想出了如何搜索簡單的 JSON 哈希;
scope :rice_flour, -> { where("ingredients ->> 'flour' = ?", "rice") }
...但這種查詢類型仍然逃脫我。 我查過的所有東西都用原始 SQL 命令列出來,我正在尋找如何編寫整潔的 Rails Scopes。
使用@>
運算符:
postgres@/> select '["a", "b"]'::jsonb @> '["a"]';
+------------+
| ?column? |
|------------|
| True |
+------------+
postgres@/> select '["a", "b"]'::jsonb @> '["c"]';
+------------+
| ?column? |
|------------|
| False |
+------------+
https://www.postgresql.org/docs/10/functions-json.html
您的范圍將類似於:
scope :rice_flour, -> {
.where("ingredients -> 'flour' @> '[\"rice\"]'::jsonb")
}
這將生成一個 SQL,如:
WHERE (ingredients -> 'flour' @> '["rice"]'::jsonb)
假設flour
是鍵, rice
是數組中的值之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.