Home > Software engineering >  LARAVEL | Group By Query Edit
LARAVEL | Group By Query Edit

Time:08-01

I'm have this query:

        $result_status_count = TWTask::whereRelation('assignee', 't_w_assignees.user_id', $user->id)
        ->groupBy('status_id', 't_w_statuses.name') // count all task group by status for all users.
        ->join('t_w_statuses', 't_w_statuses.id', 't_w_tasks.status_id')
        ->selectRaw('t_w_statuses.name, count(*)')
        ->get();

and the result is:

enter image description here

but I'm need the Result Like:

[
 {
   "Processing": 1
 },
 {
   "Rejected": 4
 },
 { 
   "Completed": 6
 }
]

CodePudding user response:

use pluck.

For example, ....->get()->pluck('count(*)','name');

CodePudding user response:

You can try with case query if you have static list of status e.g

select 
sum(case when status = 'Processing' then 1 else 0 end) Processing,
sum(case when status = 'Rejected' then 1 else 0 end) Rejected,
sum(case when status = 'Completed' then 1 else 0 end) Completed
from table_name
  • Related