Rails 带值数组的 JSONB 哈希范围
Rails Scope for JSONB Hash with Array for Value
我正在使用 JSONB 列,其中数据存储为 { key => [value, value, value ] }
如何编写 returns 记录的范围,其中包含特定键数组中的特定值?
我已经知道如何搜索简单的 JSON 哈希;
scope :rice_flour, -> { where("ingredients ->> 'flour' = ?", "rice") }
...但我仍然无法理解这种查询类型。我查找的所有内容都以原始 SQL 命令列出,我正在寻找如何编写整洁的 Rails 范围。
使用@>
运算符:
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
是数组中的值之一。
我正在使用 JSONB 列,其中数据存储为 { key => [value, value, value ] } 如何编写 returns 记录的范围,其中包含特定键数组中的特定值?
我已经知道如何搜索简单的 JSON 哈希;
scope :rice_flour, -> { where("ingredients ->> 'flour' = ?", "rice") }
...但我仍然无法理解这种查询类型。我查找的所有内容都以原始 SQL 命令列出,我正在寻找如何编写整洁的 Rails 范围。
使用@>
运算符:
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
是数组中的值之一。