【问题标题】:Query for records where json key exists in Rails/Arel/Postgresql查询 Rails/Arel/Postgresql 中存在 json 键的记录
【发布时间】:2021-09-16 14:52:23
【问题描述】:

在一个假设的 books 表上,其中有一个名为 internaljson 列,我想调用 和(分别)没有 有的记录rating 键。

【问题讨论】:

    标签: ruby-on-rails json postgresql arel


    【解决方案1】:

    存在:

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

    不存在:

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

    See table called "Additional jsonb Operators":

    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
    

    【讨论】:

    • 但是在使用? 运算符和占位符时要小心,您需要使用命名占位符:where('internal::jsonb ? :key', key: 'rating')
    • 非常感谢。我已经更新了答案。
    猜你喜欢
    • 2020-06-17
    • 2022-01-11
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    相关资源
    最近更新 更多