Laravel:循环显示多个计数

时间:2018-03-07 18:46:29

标签: mysql database laravel loops

我希望每年能够循环,并在特定年份找到特定球队的主场胜利/客场胜利。但是,我觉得我现在这样做的方式是犯罪效率低下,但我是laravel的新手,无法弄清楚到底需要什么。这是我的控制器:

  //Year 2005 First Rounds
  $roundoneyearonea= GameData::where('homeTeam', $teamdatas)->where('homeWin', '1')->where('stage', 'R16')->where('round', 'one')->where('year', '2005')->count();
  $roundoneyearoneb= GameData::where('awayteam', $teamdatas)->where('awayWin', '1')->where('stage', 'R16')->where('round', 'one')->where('year', '2005')->count();
  $roundoneyearone= $roundoneyearonea + $roundoneyearoneb;

  $roundoneyearonec= GameData::where('homeTeam', $teamdatas)->where('homeLoss', '1')->where('stage', 'R16')->where('round', 'one')->where('year', '2005')->count();
  $roundoneyearoned= GameData::where('awayteam', $teamdatas)->where('awayLoss', '1')->where('stage', 'R16')->where('round', 'one')->where('year', '2005')->count();
  $roundoneyearoneloss= $roundoneyearonec + $roundoneyearoned;

  //Year 2005 Second Rounds
  $roundtwoyearonea= GameData::where('homeTeam', $teamdatas)->where('homeWin', '1')->where('stage', 'R16')->where('round', 'two')->where('year', '2005')->count();
  $roundtwoyearoneb= GameData::where('awayteam', $teamdatas)->where('awayWin', '1')->where('stage', 'R16')->where('round', 'two')->where('year', '2005')->count();
  $roundtwoyearone= $roundtwoyearonea + $roundtwoyearoneb;

  $roundtwoyearonec= GameData::where('homeTeam', $teamdatas)->where('homeLoss', '1')->where('stage', 'R16')->where('round', 'two')->where('year', '2005')->count();
  $roundtwoyearoned= GameData::where('awayteam', $teamdatas)->where('awayLoss', '1')->where('stage', 'R16')->where('round', 'two')->where('year', '2005')->count();
  $roundtwoyearoneloss= $roundtwoyearonec + $roundtwoyearoned;

我这样做了多轮和多年,至少可以说是荒谬的。循环的建议?

1 个答案:

答案 0 :(得分:0)

您可以创建一个接收时间间隔的方法,然后使用whereIn语句

function createYearsArray()
{
    // Logic of the function

     return [
        2015,
        2016,
        2016,
    ]
 }

 $years = createYearsArray();

 $roundoneyearoned = GameData::where('awayteam', $teamdatas)
     ->where('awayLoss', '1')
     ->where('stage', 'R16')
     ->where('round', 'one')
     ->whereIn('year', $years)->count();