Laravel sum 雄辩合集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27803573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel sum eloquent collection
提问by Lovatt
How can i sum a data set that has been eager loaded?
我如何总结一个已经预先加载的数据集?
This is my table structure:
这是我的表结构:
regions table
+------------+------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------------------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| region | varchar(255) | NO | | NULL | |
| created_at | timestamp | NO | | 0000-00-00 00:00:00 | |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 | |
+------------+------------------+------+-----+---------------------+----------------+
submits table
+------------+------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------------------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| region_id | int(11) | NO | | NULL | |
| deals | int(11) | NO | | NULL | |
| created_at | timestamp | NO | | 0000-00-00 00:00:00 | |
| updated_at | timestamp | NO | | 0000-00-00 00:00:00 | |
+------------+------------------+------+-----+---------------------+----------------+
These are my models / relationships :-
这些是我的模型/关系:-
class Region extends Eloquent {
public function submits()
{
return $this->hasMany('Submit');
}
}
<?php
class Submit extends Eloquent {
public function regions()
{
return $this->belongsTo('Region');
}
}
This is my controller
这是我的控制器
public function index()
{
$regions = Region::with('submits')->get();
return $regions;
//return View::make('pages.index', compact('regions'));
}
This is what the returned data looks like (in json format, i understand $regions in an eloquent collection):-
这就是返回的数据的样子(在 json 格式中,我理解 $regions 在一个 eloquent 集合中):-
I can't figure out how i can send the sum total of 'deals' (4) back to the view?
我不知道如何将“交易”(4) 的总和发送回视图?
回答by Joseph Silber
$deals = $regions->sum(function ($region) {
return $region->submits->sum('deals');
});