首页 > 解决方案 > Laravel - 带有子查询的查询构建器

问题描述

所以我有一个如下所示的数据透视表:

match id
player id
score

我想查询以获取给定用户 ID 的赢/输数。(根据游戏中得分最高的用户 ID 获胜)

在sql中我会这样写:

SELECT user_id, score 
from match_user matchu1 
where score = (select max(score) from match_user matchu2 where matchu1.match_id = matchu2.match_id) 

我将如何在 laravel 中表达这个查询,或者有没有更好的方法来做这个我错过了?

标签: mysqlsqllaravel

解决方案


这是为了回答您提出这个问题的真正意图,即获取单个用户的获胜次数,正如您对我的回答所评论的那样。以下是我现在能想到的最佳解决方案:

class Match extends Model
{
    public function scopeWonBy($query, User $user)
    {
        return $query->selectRaw('matches.id, max(match_user.score) AS max_store, match_user.player_id AS player_id')
            ->join('match_user', 'matches.id', '=', 'match_user.match_id')
            ->groupBy('matches.id')
            ->having('player_id', $user->id);
    }
}

稍后,您可以说:

$matches = Match::wonBy($user);
$count = Match::wonBy($user)->count();

推荐阅读