【问题标题】:Query on jsonb array查询 jsonb 数组
【发布时间】:2019-07-02 08:18:22
【问题描述】:

我有这种 json 数组,我想检查值数组中的 stringValue 是否为空,另外我想用它的 id 检查它fielddata 是列名

[
  {
    "name": "50a5613e97e04cb5b8d32afa8a9975d1",
    "value": {
      "stringValue": null
    }
  },
  {
    "name": "bb127e8284c84692aa217539c4312394",
    "value": {
      "dateValue": 1549065600
    }
  }
]

查询是:

select * 
from field 
WHERE (fielddata->>'name') = '50a5613e97e04cb5b8d32afa8a9975d1' 
   AND fielddata->'value'->>'stringValue' IS NOT NULL;

我想在 laravel5.7 中使用这个查询

【问题讨论】:

    标签: json laravel postgresql


    【解决方案1】:

    试试这个

    $result = \DB::table('field')->where('name', "50a5613e97e04cb5b8d32afa8a9975d1" )->where('value', $stringValue)->get();
    
    if(isset($result)){
        foreach($result as $res){
            if(isset($res['value']->stringValue)){
                // not null case
            }else{
                // null case
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      在 SQL 查询中,我认为您需要这样的内容:

      select t.*
      from the_table t
      where exists (select *
                    from jsonb_array_elements(t.fielddata) as j(e)
                    where e ->> 'name' = '50a5613e97e04cb5b8d32afa8a9975d1' 
                      and e -> 'value' ->> 'stringValue' is not null);
      

      exists 子查询将检查每个数组元素并查看是否至少有一个元素具有指定的名称和非空stringValue。然后,查询将从满足条件的表中返回完整的行。

      在线示例:https://rextester.com/AGGJNR88809

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 2021-01-29
        • 2022-01-11
        • 1970-01-01
        • 2020-05-22
        • 2019-11-29
        • 2018-03-29
        • 1970-01-01
        相关资源
        最近更新 更多