如何在“Laravel查询”构建器中编写以下内容?
SELECT name,COUNT(*) as count FROM tablename GROUP BY name ORDER BY count DESC;
示例DB:
id name
----- ------
1 Mark
2 Mike
3 Paul
4 Mike
5 Mike
6 John
7 Mark
预期结果:
name count
----- -----
Mike 3
Mark 2
Paul 1
John 1
答案 0 :(得分:6)
DB::table('table')
->selectRaw('name, COUNT(*) as count')
->groupBy('name')
->orderBy('count', 'desc')
->get();