表中的 Laravel 总和列

Posted

技术标签:

【中文标题】表中的 Laravel 总和列【英文标题】:Laravel sum column in table 【发布时间】:2016-01-21 22:31:00 【问题描述】:

我有两张桌子:

LECTURES
id   name
1 - Lesson 1
2 - Lesson 2
3 - Lesson 3

LECTURESTYPE
id  id_lectures   numb
1 -     1 -        10
2 -     2 -        20
3 -     1 -        30

如何对每节课的 numbs 列求和并得出如下结果:name: Lesson 1 numb: 40

我想显示每节课的 numb 总和。

【问题讨论】:

【参考方案1】:

试试LECTURESTYPE::with('lectures')->GroupBy('id_lectures')->sum('numb')

【讨论】:

【参考方案2】:

你需要以下关系:

讲座(App\Lecture.php)

namespace App;
class Lecture extends Model 
    protected $table = 'lectures';
    public function lecturetype() 
        return $this->hasMany('App\LectureType');
    

LectureType (App\LectureType.php)

namespace App;
class LectureType extends Model 
    protected $table = 'lecturestype';
    public function lecture() 
        return $this->belongsTo('App\Lecture');
    

现在你可以在 Controller 中尝试了:

$sum = App\LectureType::with('lecture')->GroupBy('id_lectures')->sum('numb');

【讨论】:

$sum = App\LectureType::with('lecture')->GroupBy('id_lectures')->sum('numb'); 只回我10号没有数组【参考方案3】:

试试LECTURESTYPE::with('lectures')->sum('numb')->GroupBy('id_lectures')->get()

【讨论】:

我需要在模型中加入什么关系 对于 LECTURESTYPE 模型:public function lectures() return $this->hasMany('App\LECTURES','id_lectures'); 在 double 上调用成员函数 groupBy()

以上是关于表中的 Laravel 总和列的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 雄辩的查询与条件下另一个表中的值的总和

laravel4 更新数据透视表中的附加列

Laravel - 使用 Join 语句更新表中的所有列

如何从 laravel 7 API 中的两个表中选择特定列?

Laravel 4 中的 Eloquent 调用:处理多个表中的单个列

在 Laravel Eloquent 中使用关系表中的特定列获取表中的特定列