title: Count objects in related model if condition in third model is met
body: <p>I've got five models:</p>
  
  <ul>
  <li>Team</li>
  <li>Season</li>
  <li>Game</li>
  <li>Stat</li>
  <li>Stat_Meta</li>
  </ul>
  
  <p>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.</p>
  
  <p>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. </p>
  
  <p>This is really easy for games, because I just do this:</p>
  
  <pre><code>return $this-&gt;hasMany('App\Models\Stat', 'stat')-&gt;where('game_id', 1)-&gt;count();
  </code></pre>
  
  <p>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.</p>
  
  <p>I know this is wrong, but I tried it (it failed) to maybe make it clearer what I am trying to do here:</p>
  
  <pre><code>return $this-&gt;hasMany('App\Models\Stat', 'stat')-&gt;where('game.season_id', 7)-&gt;count();
  </code></pre>
  
  <p>Doing this gave me the following error (somewhat obviously):</p>
  
  <blockquote>
    <p>Column not found: 1054 Unknown column 'game.season_id' in 'where
    clause'</p>
  </blockquote>
  
  <p>After a lot of Googling I have yet to really find anything out about this. Any thoughts?</p>