mam*_*oha 6 ruby postgresql json ruby-on-rails
我使用Postgres的JSON数据类型来存储一些信息.
例如,我的模型User包含一个字段locations,该字段包含一个json文档(包含键和值对的对象数组),格式如下:
[{"name": "Location 1", kind: "house"},
{"name": "Location 2", kind: "house"},
{"name": "Location 3", kind: "office"},
...
{"name": "Location X", kind: "house"}
]
Run Code Online (Sandbox Code Playgroud)
我想查询.whereJSON数据类型.
我想查询至少有一个位置的用户kind = office.
谢谢!
我想查询具有类型位置的用户
office
# if locations is jsonb type
User.where('locations @> ?', { kind: 'office' }.to_json)
# if locations is json type
User.where("locations->>'kind' = 'office'")
# if locations is array of hashes
User.where('locations @> ?', [{ kind: 'office' }].to_json)
Run Code Online (Sandbox Code Playgroud)
我混合使用了上述答案。这是我的工作代码:
User.where("locations::jsonb @> ?", [{kind: 'office'}].to_json)
Run Code Online (Sandbox Code Playgroud)
作为一个说明,locations是JSON列User表(不JSONB数据类型)
| 归档时间: |
|
| 查看次数: |
2592 次 |
| 最近记录: |