【问题标题】:ActiveRecord check if any value in array matches value in array with postgresActiveRecord 使用 postgres 检查数组中的任何值是否与数组中的值匹配
【发布时间】:2017-07-31 05:13:02
【问题描述】:

我有一个整数数组,我需要找到任何记录,其中我的数组中的一个整数与使用活动记录存储在 postgres 中的数组中的任何整数相匹配。

我找到的最接近的是this answer,它适用于使用一个 int 搜索数组,但不适用于使用数组搜索。

以这种方式查找记录的最佳方法是什么?

【问题讨论】:

    标签: ruby-on-rails arrays postgresql activerecord


    【解决方案1】:

    找到一个可行的解决方案

    Model.where('array_in_db && ARRAY[?]::integer[]', [1,2,3])
    

    【讨论】:

      【解决方案2】:

      我认为最好的方法是使用重叠 (&&) postgres 运算符来完成您想要实现的目标。

      在此处查看相同的 postgres 文档 - https://www.postgresql.org/docs/9.1/static/functions-array.html

      查询看起来类似于:

      SELECT *
      FROM table_name
      WHERE column && {value1,value2};
      

      编辑:改进答案。

      在 ActiveRecord 中,您可以使用简单的 where 子句调用来构建该查询,或者最好安装 https://github.com/DockYard/postgres_ext gem 以便更轻松地集成。

      如果你安装了 postgres 扩展 gem,你可以这样做:

      Model.where.overlap(column: [value1, value2])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-27
        • 1970-01-01
        • 2019-08-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多