dongyingtang3803 2019-07-31 04:11
浏览 69

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

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条回答

  • doulun1915 2019-07-31 20:51
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝