2013-11-15 82 views
0

我使用Eloquent与我的MySql数据库交谈。我有一个teams的表,它与tasks通过tasks_teams有多对多的关系。 tasks有一列叫做points。当团队完成任务时,他们可以获得积分。雄辩多对多

我想给团队对象一个方法来返回团队赢得的总积分。此查询的SQL是这样的:

SELECT SUM(points) FROM tasks_teams, tasks WHERE 
    team_id = 1 
AND tasks_teams.task_id = tasks.id; 

这是我Team型号:

class Team extends Illuminate\Database\Eloquent\Model { 
    protected $table = 'teams'; 

    public function tasks() { 
     return $this->belongsToMany('Task', 'tasks_teams'); 
    } 
} 

我想这个方法添加到Team,但它不工作:

public function points() { 
    return $this->tasks->sum('points'); 
} 

但我得到这个:

Fatal error: Call to undefined method Illuminate\Database\Eloquent\Collection::sum() in [...]/Models/Team.php on line 19

我在这里错了什么?

回答

0

找到了potential hint at the Laravel Forums(谢谢bobodan!),试了一下它就行了。

我的解决办法:

public function points() { 
    return $this->belongsToMany('Task', 'tasks_teams')->sum('points'); 
}