Skip to content
Advertisement

How to get the value of specific index inside an array column using mysql?

This is my database table

$reports = DB::table('attendance_report_details')
            ->select('*','project_hours[$index_id]')
            ->get();

I am passing index id to the function. Is there a way to do it like this?

Advertisement

Answer

Use the arrow operator (MySQL-only):

$reports = DB::table('attendance_report_details')
    ->select('*', DB::raw("project_hours->'$[".(int) $index_id."]'"))
    ->get();

Or its alias JSON_EXTRACT() (MySQL & MariaDB):

$reports = DB::table('attendance_report_details')
    ->select('*', DB::raw("json_extract(project_hours, '$[".(int) $index_id."]')"))
    ->get();
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement