【问题标题】:Query if array column contains one or more values查询数组列是否包含一个或多个值
【发布时间】:2018-04-27 15:45:48
【问题描述】:

我有一个带有 PostgreSQL 9.6 数据库的 Rails 5 应用程序。

应用程序有Report 模型,带有department_ids 数组字段,在schema.rb 中定义为:

t.integer "department_ids", default: [], array: true

我需要编写一个查询来返回报告行,其中department_ids 列包含一个或多个给定的department_id 集。

我目前的解决方法是在 Ruby 中使用:

department_ids = [2, 5]

reports = Report.all.select do |report|
  (report.department_ids & department_ids).any?
end

但是,使用select 的缺点是返回Array 而不是ActiveRecord::Relation,这意味着我需要将过滤后的结果水合回ActiveRecord::Relation 对象。

Report.where(id: reports.map(&:id))

我想避免这一步,并在一个查询中处理这一切。

如何使用 Active Record 编写这样的查询?

【问题讨论】:

  • 为什么要使用这样的字段?也许您需要在部门中定义report_id或建立多对多关联?

标签: ruby-on-rails arrays postgresql activerecord rails-activerecord


【解决方案1】:

这样的事情应该可以工作:

Report.where('department_ids @> ARRAY[?]::integer[]', [2, 5])

您可以找到有关数组函数和运算符的更多信息here

【讨论】:

  • 对于任何想知道“@>”是什么意思的人。它是 PostgreSQL 中的“包含”运算符。它是为多种数据类型定义的——数组、范围类型、几何类型、JSON(和 JSONB)。
猜你喜欢
  • 2017-10-17
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
相关资源
最近更新 更多