【问题标题】:How to check for inclusion of a value in a nested array如何检查嵌套数组中是否包含值
【发布时间】:2016-02-19 14:12:27
【问题描述】:

在 postgres json 字段中,如何使用 ActiveRecord 查询匹配 item["editions"] 包括 23 的所有数组项?

Topic.create!(                                
  tree: [                                                                         
    {                                                                             
      "title"       => "Title 1",                                                    
      "description" => "Description",                                              
      "editions"    => [23],                                  
    }
   {                                                                             
      "title"       => "Title 2",                                                    
      "description" => "Description",                                              
      "editions"    => [12],                                  
    }                                                                                   
  ]
)          

【问题讨论】:

    标签: ruby-on-rails json rails-activerecord postgresql-9.1


    【解决方案1】:

    你有一些额外的逗号和一些缺少的逗号:我;我要整理数组到以下内容:

    myarray =  [                                                                         
      {                                                                             
        "title"       => "Title 1",                                                    
        "description" => "Description",                                              
        "editions"    => [23]                     
      },
     {                                                                             
        "title"       => "Title 2",                                                    
        "description" => "Description",                                              
        "editions"    => [12]                                
      }                                                                                   
    ]
    => [{"title"=>"Title 1", "description"=>"Description", "editions"=>[23]}, {"title"=>"Title 2", "description"=>"Description", "editions"=>[12]}]
    
    matching = myarray.select{|hash| hash["editions"].include?(23)}
    => [{"title"=>"Title 1", "description"=>"Description", "editions"=>[23]}]
    

    这就是你如何使用现有的数据结构来实现的,该结构是数组和散列的混合体。如果您想知道如何通过 sql 查询来执行此操作,则需要说明您实际上是如何将这些数据存储在数据库中的,并包含一些示例。

    【讨论】:

      猜你喜欢
      • 2019-10-10
      • 1970-01-01
      • 2012-01-10
      • 2019-08-10
      • 2021-10-01
      • 2021-09-10
      相关资源
      最近更新 更多