首页 > 解决方案 > 查询 Rails/Arel/Postgresql 中存在 json 键的记录

问题描述

在带有名为 的列的假设books表上,我想召唤有(分别)没有键的记录。jsoninternalrating

标签: ruby-on-railsjsonpostgresqlarel

解决方案


存在:

Book.where('internal::jsonb ? :key', key: 'rating')

不存在:

Book.where.not('internal::jsonb ? :key', key: 'rating')

请参阅名为“附加 jsonb 运算符”的表

jsonb ? text → boolean
Does the text string exist as a top-level key or array element within the JSON value?
'{"a":1, "b":2}'::jsonb ? 'b' → t
'["a", "b", "c"]'::jsonb ? 'b' → t

推荐阅读