Grant Gubatan
Grant Gubatan

Reputation: 265

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

I am trying to display the names of assignee arranged by the most tickets assigned_to.

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

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

Upvotes: 3

Views: 5365

Answers (4)

Bibhudatta Sahoo
Bibhudatta Sahoo

Reputation: 4894

Try like this

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

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

Upvotes: 1

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21681

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 !!!

Upvotes: 0

kunal
kunal

Reputation: 4248

Try this:-

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

Upvotes: 0

Exprator
Exprator

Reputation: 27503

you have 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();

Upvotes: 3

Related Questions