【问题标题】:How to compare if a record exist with json data type field?如何比较是否存在带有 json 数据类型字段的记录?
【发布时间】:2014-08-18 19:32:58
【问题描述】:

我想检查数据库中是否已经存在一条记录,但是我有一个 json 数据类型字段,我也需要比较它。 当我尝试使用exists? 进行检查时,出现以下错误:

SELECT  1 AS one FROM "arrangements"
WHERE "arrangements"."deleted_at" IS NULL AND "arrangements"."account_id" = 1
AND "arrangements"."receiver_id" = 19 AND "config"."hardware" = '---
category: mobile
serial: ''00000013''
vehicle: 
' AND "arrangements"."recorded" = 't' LIMIT 1

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "config"
LINE 1: ...id" = 1 AND "arrangements"."receiver_id" = 19 AND "config"."...
                                                         ^

我用来检查 a 是否存在的代码:

@arrangement = Arrangement.new({account_id: receiver.account.id, receiver_id: receiver.id, config: params[:config], recorded: true})

if Arrangement.exists?(account_id: @arrangement.account_id, receiver_id: @arrangement.receiver_id, config: @arrangement.config, recorded: @arrangement.recorded)
    puts 'true'
end

我已经试过了:

if Arrangement.exists?(@arrangement)
   puts 'true'
end

但总是返回 false

表:

create_table :arrangements do |t|
  t.references :account,    index:   true
  t.references :receiver,   index:   true
  t.json       :config,     null:    false
  t.boolean    :recorded,   default: false
  t.datetime   :deleted_at, index:   true
  t.integer    :created_by
  t.timestamps
end

【问题讨论】:

  • 我猜AND "config"."hardware" 应该是AND "arrangements"."config" ??
  • 很难比较整个json 值。 json 数据类型只是一个容器,对于定义的整个值没有相等运算符(没有 =)。在即将推出的 Postgres 9.4 中,您会喜欢 jsonb,它具有该功能。 More details

标签: ruby-on-rails postgresql ruby-on-rails-4 rails-postgresql postgresql-9.3


【解决方案1】:

你不能比较 jsons。尝试比较一些 jsons 值

where("arrangements.config->>'category' = ?", params[:config][:category])

查看 in postgresql docs 以了解其他 JSON 函数和运算符

【讨论】:

    【解决方案2】:

    这会将字段(如果只是json)和参数(将是一个json字符串)转换为jsonb,然后对其包含的所有内容进行比较。

    def existing_config?(config)
      Arrangement.where("config::jsonb = ?::jsonb", config.to_json).any?
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多