Laravel whereJsonContains 具有多维数组

问题描述 投票:0回答:2

我在 MySQL 8 中确实有一个 JSON 类型的数据库字段

attributes
。该字段包含具有以下格式的 JSON 字符串:

    {
    "094e4f67-f427-4c3c-9f98-1d45585596de": {
        "price": 4.66,
        "title": "Prissy Pink",
    },
    "0b6ce397-af06-484a-bf6b-cfc92333f838": {
        "price": 4.66,
        "title": "Cameo Rose",
    },
    "0baf95f8-6ee5-47da-b827-69dc160c7127": {
        "price": 4.75,
        "title": "Petrol Blue",
    }
}

现在我想使用 Laravel 8/Eloquent 查询此 JSON 字段,以查找属性标题为“Petrol Blue”的所有产品。

当我尝试时

Product::whereJsonContains('attributes->title','Petrol Blue') 

我没有得到任何结果 - 因为我认为是多数组。

如何正确查询?

Product::whereJsonContains('attributes->*->title,'Petrol Blue') 

也不起作用。

我什至尝试过

Product::whereJsonContains('attributes.*.title,'Petrol Blue') 

没有结果。

有什么想法吗?

mysql laravel eloquent mysql-json
2个回答
0
投票

我认为你的json应该是这样的:

[
    "094e4f67-f427-4c3c-9f98-1d45585596de": {
        "price": 4.66,
        "title": "Prissy Pink",
    },
    "0b6ce397-af06-484a-bf6b-cfc92333f838": {
        "price": 4.66,
        "title": "Cameo Rose",
    },
    "0baf95f8-6ee5-47da-b827-69dc160c7127": {
        "price": 4.75,
        "title": "Petrol Blue",
    }
]

不是这样的

{
    "094e4f67-f427-4c3c-9f98-1d45585596de": {
        "price": 4.66,
        "title": "Prissy Pink",
    },
    "0b6ce397-af06-484a-bf6b-cfc92333f838": {
        "price": 4.66,
        "title": "Cameo Rose",
    },
    "0baf95f8-6ee5-47da-b827-69dc160c7127": {
        "price": 4.75,
        "title": "Petrol Blue",
    }
}
Product::whereJsonContains('attributes', [['title' => 'Petrol Blue']])->get();

0
投票

试试这个:

Product::whereJsonContains('attributes', function($query) {
  $query->where('title', 'Petrol Blue');
})->get();
© www.soinside.com 2019 - 2024. All rights reserved.