Laravel联赛管理系统更新积分榜报错:参数传递异常
Laravel联赛管理系统积分榜更新参数错误修复
问题概述
开发Laravel联赛管理系统时,提交比赛结果触发报错:
Too few arguments to function App\Models\Gamescores::updateStandings(), 0 passed in E:\Video\laraVids\laraProjects\HAM\app\Models\Gamescores.php on line 28 and exactly 1 expected
核心问题是updateStandings方法要求传入$league_id,但模型的created事件调用时未传参,同时代码存在冗余查询、重复更新的问题。
修复方案
1. 修正模型created事件的参数传递
在Gamescores模型的boot方法中,通过关联关系直接获取当前比赛所属的联赛ID,再传入updateStandings:
public static function boot() { parent::boot(); static::created(function ($gamescore) { // 利用关联关系获取联赛ID,避免额外查询 $league_id = $gamescore->game->league_id; $gamescore->updateStandings($league_id); }); }
2. 优化updateStandings方法逻辑
原方法会遍历所有联赛的比赛记录,效率低下且存在重复查询。调整为仅更新当前比赛对应的球队积分:
public function updateStandings($league_id) { // 直接使用当前gamescore关联的game模型,无需重复查询 $game = $this->game; $home_team_id = $game->home_team; $away_team_id = $game->away_team; // 更新主队积分榜 $home_team_log = Logtable::where('team_id', $home_team_id)->first(); if ($home_team_log !== null) { $home_team_log->played += 1; if ($this->home_score > $this->away_score) { $home_team_log->won += 1; $home_team_log->points += 3; } elseif ($this->home_score == $this->away_score) { $home_team_log->drawn += 1; $home_team_log->points += 1; } else { $home_team_log->lost += 1; } $home_team_log->goals_for += $this->home_score; $home_team_log->goals_against += $this->away_score; $home_team_log->goal_difference = $home_team_log->goals_for - $home_team_log->goals_against; $home_team_log->save(); } // 更新客队积分榜 $away_team_log = Logtable::where('team_id', $away_team_id)->first(); if ($away_team_log !== null) { $away_team_log->played += 1; if ($this->away_score > $this->home_score) { $away_team_log->won += 1; $away_team_log->points += 3; } elseif ($this->home_score == $this->away_score) { $away_team_log->drawn += 1; $away_team_log->points += 1; } else { $away_team_log->lost += 1; } $away_team_log->goals_for += $this->away_score; $away_team_log->goals_against += $this->home_score; $away_team_log->goal_difference = $away_team_log->goals_for - $away_team_log->goals_against; $away_team_log->save(); } }
3. 清理控制器冗余代码
控制器fixtureToView方法中存在重复调用updateStandings的逻辑,且遍历所有比赛记录会导致重复更新积分,移除冗余部分并优化积分榜查询:
public function fixtureToView($league) { $games = Games::where('league_id', $league)->get(); $pluckedFixtures = $games->pluck('Fixture')->toArray(); $counts = array_count_values($pluckedFixtures); $fixtures = collect([]); foreach ($counts as $key => $count) { $fixtures->push($games->where('Fixture', $key)); } // 仅查询当前联赛的球队积分榜,按积分降序排列 $standings = Logtable::whereHas('team', function ($query) use ($league) { $query->where('league_id', $league); })->orderByDesc('points')->get(); return view( 'admin.league.fixtures.index', compact('fixtures', 'standings') ); }
4. 确认关联关系有效性
确保Game模型与League、Team的关联配置正确,保证$gamescore->game->league_id能正常获取到联赛ID,Logtable与Team的关联逻辑无误。
内容的提问来源于stack exchange,提问作者JesterChamba
相关产品推荐
相关产品推荐

