mysql - 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 中表达这个查询,或者有没有更好的方法来做这个我错过了?
解决方案
这是为了回答您提出这个问题的真正意图,即获取单个用户的获胜次数,正如您对我的回答所评论的那样。以下是我现在能想到的最佳解决方案:
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();
推荐阅读
- json - JSON解析Windows文件路径
- angularjs - 在显示双 y 轴的同时显示多条绘图线
- mysql - 如何修复 asp.net core 中的“MySql.Data.MySqlClient.MySqlException: 'Unknown column 'Key' in 'field list'”错误和 mysql hangfire 问题?
- php - 如何从表单中获取多个值并用php分隔它们
- php - 如何解决 Laravel 中 URL 路由的问题?
- python - Python 默认参数列表——不一致的行为
- c# - 是否可以在运行时安装包的本地版本并使用所述本地包?
- java - 选择性地替换子字符串
- javascript - 从 NodeJS 生成两次 python 脚本会与 stdout.flush 返回值混淆吗?
- redis - Redis 流限制