使用“Laravel查询”构建器计算不同值的出现次数

时间:2014-12-28 20:40:38

标签: mysql laravel

如何在“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

1 个答案:

答案 0 :(得分:6)

DB::table('table')
  ->selectRaw('name, COUNT(*) as count')
  ->groupBy('name')
  ->orderBy('count', 'desc')
  ->get();