[英]Laravel get the position/rank of a row in collection
我有一个排行榜和leaderboard_scores表。
Leaderboard_scores具有以下列: id , Leaderboard_id , player_id , score 。
在排行榜模型中,我与LeaderboardScore定义了hasMany关系:
public function scores()
{
return $this->hasMany('App\LeaderboardScore')->orderBy('score', 'desc');
}
现在,我想获得某个排行榜中玩家的排名。
因此,在控制器中,我执行了一个循环以找到给定player_id的位置:
$score = $leaderboard->scores;
$scoreCount = $scores->count();
$myScore = $scores->where('player_id', $request->query('player_id'));
if ($myScore) { // If got my score
$myRank = 1;
for ($i = 0; $i < $scoreCount; $i++) {
if ($scores[$i]->player_id == $request->query('player_id')) {
$myRank = $i + 1;
break;
}
}
// Output or do something with $myRank
}
效果很好,但是当我有十万名玩家并且他们不断获得排名时,我担心性能。 for循环似乎不是一个好的选择。
我应该使用原始数据库查询吗? 还是更好的主意?
这里有一些想法
检查缓存: https : //laravel.com/docs/5.4/redis
Mysql排名: http : //www.folkstalk.com/2013/03/grouped-rank-function-mysql-sql-query.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.