简体   繁体   中英

Eloquent many-to-many sum

I'm using Eloquent to talk to my MySql database. I have a table of teams that has a many-to-many relationship with tasks via tasks_teams . tasks has a column called points . When teams complete tasks, they earn points.

I want to give the Team object a method to return the total points that team has earned. The SQL for this query is this:

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

This is my Team model:

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

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

I want to add this method to Team , but it doesn't work:

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

but I get this:

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

What am I getting wrong here?

Found a potential hint at the Laravel Forums (thanks bobodan!), tried it and it worked.

My solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM