Home > Enterprise >  How to write this query in Laravel Eloquent
How to write this query in Laravel Eloquent

Time:05-02

The query is SELECT country, count(*) as count FROM visitors GROUP BY country ORDER BY count DESC. How to write with Visitor model eloquently?

CodePudding user response:

Visitor::query()->groupBy('country')->orderByDesc('count')->select('country' ,DB::raw('COUNT(1) as count'))->get()

CodePudding user response:

You could try somthing like this

Visitor::select('country')
     ->withCount('id')
     ->groupBy('country')
     ->latest()
     ->get()
  • Related