dongtuhe0506 2019-03-13 15:41
浏览 165

如何使用Laravel(Eloquent的)地图集合函数重构php foreach

I've just watched Adam Wathan's video on Refactoring Loops and Conditionals, and feel like I can use the map collection method in the sumLeagueStats method on my Team model (rather than the foreach).

I have a relationship on teams -> leagues, and the getLeagueStats function gets all of the stats (played, won, drew, lost, for, against, points) from the leagues table for the relevant team.

In the sumLeagueStats method I was going to use a foreach loop and loop through each stat by year, and take the sum of all of the played, etc, and return it, but having watched the above video,

class Team extends Model {

    public function league()
    {
        return $this->hasMany('league');
    }

    public function getLeagueStats($year = [2018])
    {
        return $this->league()->whereIn('year', [$year])->get();
    }

    public function sumLeagueStats($year = [2018])
    {
        foreach {
            ...
            return
        }
        /*
        * Want to return a colleciton with the following:
        *
        $this->getLeagueStats()->sum('played');
        $this->getLeagueStats()->sum('won');
        $this->getLeagueStats()->sum('drew');
        $this->getLeagueStats()->sum('lost');
        $this->getLeagueStats()->sum('for');
        $this->getLeagueStats()->sum('against');
        $this->getLeagueStats()->sum('points');
        */
    }
}

I'm new to Laravel, so firstly want to check. my suspicions are correct, and secondly looking for any insight/resource for more information, as the docs are slightly lacking).

  • 写回答

1条回答 默认 最新

  • doupao1530 2019-03-13 15:50
    关注

    Calling getLeagueStats everytime is making a request to your database everytime you call the sum method, so you can create a variable to work with and create a collection that represents the data :

    $stats = $this->getLeagueStats();
    return collect([
        'played' => $stats->sum('played'),
        'won' => $stats->sum('won'),
        'drew' => $stats->sum('drew'),
        'won' => $stats->sum('won'),
        'lost' => $stats->sum('lost'),
        'for' => $stats->sum('for'),
        'points' => $stats->sum('points')
    ]);
    

    is that a what you want ?

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题