雄辩的PostgreSQL JSONB和嵌套数组

时间:2019-10-15 10:59:23

标签: arrays json eloquent laravel-6

我在使用PostgreSQL作为数据库的Laravel 6应用程序中搜索嵌套JSON数组时遇到麻烦。

迁移:

$table->bigIncrement('id');
$table->string('comment')->nullable();
$table->jsonb('result')->nullable()

型号:

protected $casts = [
    'result' => 'json'
];

JSON示例:

{
  "suggestions": [
    {
      "value": "short value",
      "unrestricted_value": "full lenght value",
      "data": {
        "postal_code": "",
        "country": "",
        "country_iso_code": "RU",
        ...
        other fields
        ...
        "qc": null
      }
    }
  ]
}

我需要按country_iso_code查询JSON。

我尝试过的命令:

>>> Model::where('result->suggestions->0->data->country_iso_code', 'RU')->first()
=> null
>>> Model::where('result->suggestions->data->country_iso_code', 'RU')->first()
=> null
>>> Model::where('result->suggestions.data->country_iso_code', 'RU')->first()
=> null
>>> Model::where('result->suggestions->data->country_iso_code', 'RU')->first()
=> null
>>> Model::whereJsonContains('result->suggestions', ['data->country_iso_code' => 'RU'])->first()
=> null
>>> Model::whereJsonContains('result', ['suggestions' => ['data->country_iso_code' => 'RU']])->first()
=> null

我需要帮助,我被困住了。预先谢谢你。

注意:我无法修改数据库表和数据的存储方式,因为数据已与其他应用程序共享。

PS:对不起,英语不好,这不是我的母语

1 个答案:

答案 0 :(得分:0)

我应该使用数组模式进行搜索

Model::whereJsonContains('result', ['suggestions' => [0 => ['data' => ['country_iso_code' => 'RU']]]])->first()

返回预期数据