Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 检查JSONB列中的数组是否包含其他数组中的任何值_Ruby On Rails_Postgresql_Activerecord - Fatal编程技术网

Ruby on rails 检查JSONB列中的数组是否包含其他数组中的任何值

Ruby on rails 检查JSONB列中的数组是否包含其他数组中的任何值,ruby-on-rails,postgresql,activerecord,Ruby On Rails,Postgresql,Activerecord,问题 查找样本数据中的所有记录,其中foo->bar至少包含给定数组中的一项,例如[1,2] 样本数据 Record 1 => 'foo': { 'bar': [1,2] } Record 2 => 'foo': { 'bar': [3,4] } Record 3 => 'foo': { 'bar': [5,7] } Record 4 => 'foo': { 'bar': [1] } Record 5 => 'foo': { 'bar':

问题

查找样本数据中的所有记录,其中
foo->bar
至少包含给定数组中的一项,例如[1,2]

样本数据

Record 1 => 'foo': {
  'bar': [1,2]
}

Record 2 => 'foo': {
  'bar': [3,4]
}

Record 3 => 'foo': {
  'bar': [5,7]
}

Record 4 => 'foo': {
  'bar': [1]
}

Record 5 => 'foo': {
  'bar': [2,3]
}
预期结果

Record 1 => 'foo': {
  'bar': [1,2]
}


Record 4 => 'foo': {
  'bar': [1]
}

Record 5 => 'foo': {
  'bar': [2,3]
}
我尝试使用操作符
@>
?|
,第一次检查JSOB并仅在包含所有项时返回。第二个问题是类型JSOB=>Integer[]

SQL

SELECT  "some_table".* FROM "some_table" WHERE (foo->'bar' @> '[1,2]'::jsonb);
轨道范围

scope :for_bar, -> (bars) { where("foo->'bar' @> ?::jsonb", bars.to_json) }

解决此问题的任何建议。

一种可能的解决方案是使用
jsonb_array_elements()
将JSON数组展开为多个集合。然后,在
EXISTS
子查询中,在公共元素上内部联接这些集合

SELECT *
       FROM some_table
       WHERE EXISTS (SELECT *
                            FROM jsonb_array_elements(some_table.foo->'bar') t (v)
                                 INNER JOIN jsonb_array_elements('[1,2]'::jsonb) s (v)
                                            ON t.v = s.v);

我想你需要的是:

  • 从foo中提取bar
  • 条中的任何元素映射到JSON
  • 将绑定值强制转换为
    数组
  • 将绑定值数组强制转换为
    jsonb[]
  • 检查左JSON值中的
    是否有任何
    在顶层包含右JSON路径/值项(
    @>
    ):

完全有道理,非常感谢。
SomeTable.where("foo->'bar' @> ANY(ARRAY[?]::JSONB[])", [1, 2].map(&:to_json))