如何解决如何在Rails中的数组内部使用哈希查询JSON数据?
我在Note模型上有以下数据集。目前,我正在使用Postgres作为数据库。以下是Notes
表上的两条不同记录。
id: 1,name: 'First Note',items: [{description: 'First Note'},{description: 'PM1 Second Note'}]
id: 2,name: 'Second Note',items: [{description: 'Second Note'},{description: 'PM2 Second Note'}]
id: 3,name: 'Third Note',items: [{description: 'Third Note'},{description: 'Invalid Second Note'}]
如何查询json
字段(项目),以便我获得描述字段上值为PM
的所有注释,即查询应返回上例中ID为1和2的注释?
解决方法
使用原始SQL,您可以通过以下方式实现:
select * from notes,json_array_elements(items) element
where element->>'description' LIKE '%PM%';
使用activerecord尝试以下操作:
Note.where("EXISTS (SELECT FROM json_array_elements(items) element WHERE element->>'description' LIKE '%PM%')")
,
我没有测试,但是以下其中一项应该可以工作。
Note.where("items->>'description' iLIKE ?",'%PM%')
# or
Note.where("items::json -> 'description' iLIKE ?",'%PM%')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。