如何使用 Laravel 查询生成器搜索 json 数组对象?

Shu*_*ker 5 php laravel laravel-5

这是 json 数组

"section_4": {
"data": [
{
"grade": "3.0",
"degree": "BSCSE",
"end_date": "2019-03-28T10:35:00.000Z",
"institute": "DIU",
"start_date": "2019-03-25T10:35:00.000Z"
},
{
"grade": "4.0",
"degree": "BSCSE",
"end_date": "2019-04-30T10:50:00.000Z",
"institute": "STU",
"start_date": "2019-03-31T10:50:00.000Z"
}
],
"type": "education",
"title": "Educations"
},
Run Code Online (Sandbox Code Playgroud)

想要使用成绩进行搜索,是否可以使用查询生成器进行搜索?

$resumes = UserMeta::with(['user.resume' => function ($query) {
                $query->where('data->section_4->type', 'like', '%education%');
        }])->paginate(10);
Run Code Online (Sandbox Code Playgroud)

这是尝试在控制器中搜索的代码。是否可以使用查询构建器 laravel 进行成绩搜索?

Ami*_*ari 5

要在 laravel 中的 json 数组中搜索,您可以使用以下方法:例如,您想从“data”数组中检查“grade”中的值:

$resumes = UserMeta::with(['user.resume' => function ($query) {
            $query->whereJsonContains('data->data', ['grade' => "3.0"]);
    }])->paginate(10);
Run Code Online (Sandbox Code Playgroud)

完毕....


Ift*_*din 2

Laravel 提供了whereJsonContains这样你可以尝试下面的代码:

$resumes = UserMeta::with(['user.resume' => function ($query) {
                $query->whereJsonContains('data->section_4->type', 'like', '%education%');
        }])->paginate(10);
Run Code Online (Sandbox Code Playgroud)

或者在这种情况下 您也可以whereRaw结合使用JSON_CONTAINS

例如

whereRaw("JSON_CONTAINS(type, '[education]' )")->get();
Run Code Online (Sandbox Code Playgroud)

更多内容请查看这篇文章