【问题标题】:Eloquent many-to-many sum雄辩的多对多和
【发布时间】:2013-11-15 01:56:16
【问题描述】:

我正在使用 Eloquent 与我的 MySql 数据库通信。我有一张teams 的表,它通过tasks_teamstasks 具有多对多关系。 tasks 有一个名为 points 的列。当团队完成任务时,他们会获得积分。

我想给 Team 对象一个方法来返回该团队获得的总积分。这个查询的 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');
}

但我明白了:

致命错误:在第 19 行的 [...]/Models/Team.php 中调用未定义的方法 Illuminate\Database\Eloquent\Collection::sum()

我在这里做错了什么?

【问题讨论】:

    标签: php mysql sql eloquent


    【解决方案1】:

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

    我的解决方案:

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

    【讨论】:

      猜你喜欢
      • 2014-10-08
      • 2014-05-23
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 2014-09-27
      相关资源
      最近更新 更多