Laravel循环通过特定条件显示前2

时间:2018-02-28 19:17:48

标签: mysql database laravel

我希望展示小组赛阶段(想想世界杯)并突出赢家/输家。我试图每年展示每组中的前两支球队。

 $groupbwins = LoserData::select('team')->where('stage', 'group')->where('stageSeries', 'B')->where('ar', $id)->where('win', '1')->take('2')->get();

take(2)产生每组拥有Win的前两支球队,但不是每组获胜最多的球队。如何通过throughand循环显示获得最多胜利的团队(尝试过orderby和groupby,但无法使其工作)或者我是否需要重新安排数据库以便每个团队列出团队中的获胜者作为获胜的团队那个小组中的第一个?

1 个答案:

答案 0 :(得分:0)

+----+----+------+-------+------------+-------------+
| id | ar | win  | stage | team       | stageSeries |
+----+----+------+-------+------------+-------------+
|  1 | 1  |    1 | group | carlton    | B           |
|  2 | 1  |    1 | group | carlton    | B           |
|  3 | 1  |    1 | group | west coast | C           |
|  4 | 1  |    0 | group | west coast | C           |
|  5 | 1  |    1 | group | west coast | B           |
|  6 | 1  |    0 | group | carlton    | A           |
|  7 | 1  |    1 | group | west coast | A           |
|  8 | 1  |    1 | group | carlton    | B           |
|  9 | 1  |    1 | group | carlton    | A           |
| 10 | 1  |    0 | group | west coast | C           |
| 11 | 1  |    0 | group | west coast | C           |
| 12 | 1  |    1 | group | west coast | A           |
| 13 | 1  |    1 | group | carlton    | A           |
| 14 | 1  |    1 | group | west coast | B           |
| 15 | 1  |    1 | group | west coast | B           |
| 16 | 1  |    1 | group | carlton    | B           |
| 17 | 1  |    1 | group | hawthorn   | B           |
| 18 | 1  |    1 | group | hawthorn   | B           |
| 19 | 1  |    1 | group | hawthorn   | A           |
+----+----+------+-------+------------+-------------+

您可以使用此Eloquent构建器:

LoserData::selectRaw('team, sum(win) as winTotal')
  ->where('stage', 'group')
  ->where('stageSeries', 'B')
  ->where('ar', 1)
  ->groupBy('team')
  ->orderBy('winTotal', 'desc')
  ->take('2');

哪会产生此查询:

select team, sum(win) as winTotal from `loser_datas` where `stage` = ? and `stageSeries` = ? and `ar` = ? group by `team` order by `winTotal` desc limit 2