使用Laravel查询选择并汇总多个列以进行统计

时间:2017-07-19 12:22:11

标签: laravel laravel-4

我有一个表scores,我保存了用户分数。它看起来像这样

table `scores`

id | points | user_id
 1     5          1
 2     2          1
 3     4          1
 4     1          3
 5     10         2

我想选择每个用户,总结他的积分并显示为排名。上面的结果应该是

user_id | points
  1         11
  2         10
  3         1

我提出的查询是

$sumPoints = Scores::select( \DB::raw("sum(points) as numberOfPoints"), \DB::raw("count(id) as numberId"))->groupBy("user_id")->first();

问题出在->first(),因为它只返回一个结果..它正在运行。如果我尝试使用->get()而我发现Undefined property错误。我该怎么用?

在phpmyadmin中运行的查询

SELECT count(id) as numberId, sum(points) as numberOfPoints FROM `points` GROUP BY `user_id`

1 个答案:

答案 0 :(得分:0)

你可以使用这样的东西

$sumPoints = Scores::select( \DB::raw("sum(points) as numberOfPoints"), \DB::raw("count(id) as numberId"))->groupBy("user_id")->get();
foreach($sumPoints as $point){
      dd($point); //OR dd($point->numberOfPoints)
}