在查询生成器中计数JSON数组

问题描述 投票:1回答:1

我对Laravel还是很陌生,所以这是我的exam_schedules表中的SQLyog中student_id列的JSON数组:

|----------------------------|
|      student_id            |
|------------------- --------|
|  {"id": [34, 35, 28, 36]}  |         
|----------------------------|
|  {"id": [2, 78]}           |         
|----------------------------|
|  {"id": [7, 34]}           |         
|----------------------------|
|  {"id": [8, 28, 20]}       |         
|----------------------------|

这是控制器的一部分:

$columns = [
            'faculties.name AS faculty_name',
            'courses.name AS course_name',
            'st.name AS staff_name',
            'fc.name AS venue',
            \DB::raw('DATE_FORMAT(CAST(exam_schedules.exam_from_at AS DATE), "%d/%m/%Y") AS exam_date'),
            \DB::raw('DATE_FORMAT(exam_schedules.exam_from_at, "%h:%i %p") AS time_start'),
            \DB::raw('DATE_FORMAT(exam_schedules.exam_to_at, "%h:%i %p") AS time_end'),
            'exam_schedules.remarks AS remarks',
            'exam_schedules.student_id AS total_student'
           ];

$schedule_list  = \DB::table('exam_schedules')
                    ->Join('courses', 'courses.id', '=', 'exam_schedules.course_id')
                    ->Join('faculties', 'faculties.id', '=', 'exam_schedules.faculty_id')
                    ->leftJoin('facilities AS fc', 'fc.id', '=', 'exam_schedules.facility_id')
                    ->leftJoin('staffs AS st', 'exam_schedules.staff_id', '=', 'st.id')
                    ->whereNull('exam_schedules.deleted_at')
                    ->whereNotNull('exam_schedules.exam_to_at')
                    ->whereNotNull('exam_schedules.exam_from_at')
                    ->whereNotNull('exam_schedules.exam_to_at');

我如何计算student_id看起来像这样?:

|-------------------------|
|      Total Students     |
|-------------------------|
|             4           |         
|-------------------------|
|             2           |         
|-------------------------|
|             2           |         
|-------------------------|
|             3           |         
|-------------------------|
json laravel
1个回答
0
投票

您可以使用mysql函数JSON_LENGTH()来计算json对象。

因此在您的列数组中更改total_student行:

发件人:

$columns = [
      'exam_schedules.student_id AS total_student'
     ];

至:(这将使您获得id中的元素数)

$columns = [
   \DB::raw("JSON_LENGTH(exam_schedules.student_id,'$.id') as total_students")
  ];

参考:https://database.guide/json_length-return-the-length-of-a-json-document-in-mysql/

© www.soinside.com 2019 - 2024. All rights reserved.