Select 并使用 Laravel 查询对多列求和以用于统计目的
Select and sum multiple columns for statistic purposes with Laravel query
我有一个 table scores
用于保存用户分数。看起来像这样
table `scores`
id | points | user_id
1 5 1
2 2 1
3 4 1
4 1 3
5 10 2
我想select每个用户,将他的积分加起来显示为排名。上面的结果应该是
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()
中,因为它 return 只有一个结果..它正常工作。如果我尝试使用 ->get()
而不是 Undefined property
错误。我该如何使用它?
正在 phpmyadmin 中运行的查询
SELECT count(id) as numberId, sum(points) as numberOfPoints FROM `points` GROUP BY `user_id`
你可以使用这样的东西
$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)
}
我有一个 table scores
用于保存用户分数。看起来像这样
table `scores`
id | points | user_id
1 5 1
2 2 1
3 4 1
4 1 3
5 10 2
我想select每个用户,将他的积分加起来显示为排名。上面的结果应该是
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()
中,因为它 return 只有一个结果..它正常工作。如果我尝试使用 ->get()
而不是 Undefined property
错误。我该如何使用它?
正在 phpmyadmin 中运行的查询
SELECT count(id) as numberId, sum(points) as numberOfPoints FROM `points` GROUP BY `user_id`
你可以使用这样的东西
$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)
}