Laravel 5.2 - 从我的查询

时间:2016-11-29 15:43:07

标签: php laravel laravel-5.2

我有这样的查询:

$players = PostBalance::where('post_id', $post->id)->orderBy('id','desc')->get();

效果很好并返回包含所有值的数组,帖子余额包含字段:

ID
score
post_id
user_id

我想删除user_id重复并获取最高分数值。例如,如果我有:

[0] = 'id' => 1 , 'score'=> 10, 'user_id'=> 1, 'post_id' => 1
[1] = 'id' => 2 , 'score'=> 20, 'user_id'=> 1, 'post_id' => 1
[2] = 'id' => 3 , 'score'=> 30, 'user_id'=> 1, 'post_id' => 1
[3] = 'id' => 4 , 'score'=> 40, 'user_id'=> 2, 'post_id' => 1
[4] = 'id' => 5 , 'score'=> 50, 'user_id'=> 2, 'post_id' => 1
[5] = 'id' => 6 , 'score'=> 60, 'user_id'=> 2, 'post_id' => 1

我想删除重复项user_id并仅获取具有最高分数的user_id:

结果:

[0] = 'id' => 3 , 'score'=> 30, 'user_id'=> 1, 'post_id' => 1
[1] = 'id' => 6 , 'score'=> 60, 'user_id'=> 2, 'post_id' => 1

1 个答案:

答案 0 :(得分:4)

您可以像这样使用groupBy()max()方法(注意:这实际上不会删除数据库中的重复项,但适用于您的查询):

$result = PostBalance::groupBy('user_id')
                    ->max('score');

有关详细信息,请参阅Laravel Docs

或者如果您想按score订购结果,可以这样做:

$result = PostBalance::orderBy('score', 'desc')
                     ->groupBy('user_id')
                     ->get();

注意:要获得分组的最大值,请尝试先运行orderBy(),然后在查询上运行groupBy()

希望这有帮助!