gpt4 book ai didi

postgresql - jsonb 属性列的 AR 查询

转载 作者:行者123 更新时间:2023-11-29 14:36:13 24 4
gpt4 key购买 nike

我正在为我的数据库使用 Postgres,我的拍卖模型中有一个列作为 jsonb 列。我想创建一个查询来搜索拍卖的 json 列,以查看用户名或电子邮件是否存在于任何拍卖实例的 json 列中。

现在我有 @auctions = Auction.where('invitees @> ?', {current_user.name.downcase => current_user.email.downcase}.to_json),但这只会带来返回完全匹配的 key => value 我想知道名称或电子邮件是否存在。

最佳答案

  1. 您正在使用 @> 运算符。它的描述是这样的:

    “Does the left JSON value contain the right JSON path/value entries at the top level?”

    如果您想在键(在您的情况下为名称)匹配时返回一行,您可能需要 ? 运算符。

  2. 没有一种只在 JSON 列 ( see this answer for more details ) 中搜索值的好方法,但您可以检查键是否单独存在或是否存在键和值匹配。

  3. 与使用非 JSON 列时相同的 ActiveRecord 方法和链接适用,即 wherewhere(…).or(where(…)) :

    class Auction
    def self.by_invitee(user)
    name = user.name.downcase
    json = { name => user.email } # note: you should be downcasing emails anyways
    where('invitee ? :name', name: name).or(
    where('invitee @> :json', json: json)
    )
    end
    end

关于postgresql - jsonb 属性列的 AR 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44377821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com