Laravel 5.4: How to order by count (column) eloquent?

I'm trying to display assignee names sorted by most tickets assigned_to

.

$accesses = Access::where('state','=','Assigned');

$all = Report::where('state', '=', 'Assigned')
               ->union($accesses)
               ->orderBy('count(assigned_to)') //THIS IS WRONG
               ->get();

      

+3


source to share


4 answers


you need to use DB::raw

to get it



$all = Report::where('state', '=', 'Assigned')
            ->select(DB::raw('count(reports.assigned_to) as assigned_to'))
            ->union($accesses)
            ->orderBy('assigned_to','DESC') 
            ->get();

      

+2


source


try it



$accesses = Access::where('state','=','Assigned');

$all = Report::where('state', '=', 'Assigned')
                ->union($accesses)
                ->orderBy(DB::raw('count(assigned_to)'),'DESC') 
                ->get();

      

+1


source


Try this: -

$all = Report::where('state', '=', 'Assigned')
             ->select(DB::raw('count(reports.assigned_to) as assigned_to'))
            ->union($accesses)
            ->orderBy('assignedto','DESC') 
            ->get();

      

0


source


I think you can try this:

$all = Report::where('state', '=', 'Assigned')
            ->select(DB::raw('count(reports.assigned_to) as assigned_to'),DB::raw('count(access.assigned_to) as assigned_to_access'))
            ->leftjoin('access','report.access.id','=','access.id')
            ->union($accesses)
            ->orderBy('assigned_to','DESC')
            ->orderBy('assigned_to_access','DESC') 
            ->get();

      

Hope this help for you.

0


source







All Articles