如果满足第三个模型中的条件,则计算相关模型中的对象

I've got five models:

  • Team
  • Season
  • Game
  • Stat
  • Stat_Meta

Teams have seasons, seasons have games, and games have stats, and each stat relates to a stat_meta. The stat_meta table is basically static, and it's there to classify stats by type.

I am working on a function in the Stat_Meta table so that I can call for any particular stat type (or stat_meta) to be counted within the confines of a given game, season, or team.

This is really easy for games, because I just do this:

return $this->hasMany('App\Models\Stat', 'stat')->where('game_id', 1)->count();

However, since stats are not directly related to a season or team (they are related by the game being related to both) that gets really hairy.

I know this is wrong, but I tried it (it failed) to maybe make it clearer what I am trying to do here:

return $this->hasMany('App\Models\Stat', 'stat')->where('game.season_id', 7)->count();

Doing this gave me the following error (somewhat obviously):

Column not found: 1054 Unknown column 'game.season_id' in 'where clause'

After a lot of Googling I have yet to really find anything out about this. Any thoughts?

1个回答

TL;DR, withCount() - https://laravel.com/docs/5.8/eloquent-relationships#counting-related-models

Maybe you could achieve this by taking the Season, then the games then counting the stat you want. It will look something like this

$statIdenticator = 'somethingYouAreSearchingInStats';
$season = Season::with(['games' => function($q1) use($statIdenticator) {
     return $q1->withCount(['stats' => function($q2) use($statIdenticator) {
         return $q2->where('statIdenticator', $statIdenticator);
     }]);
}])->find($seasonId);

Did not tested it, but it should give you a stats_count parameter on each games. At this point you only need to do this $season->games->sum('stats_count')

Do not copy paste, ther is not enough information about your code to be sure that will work.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐