11 months ago

Count objects in related model if condition in third model is met

Posted 11 months ago by hunterhawley

I've got five models:






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?

Please sign in or create an account to participate in this conversation.