Laravel 和雄辩合集
Posted
技术标签:
【中文标题】Laravel 和雄辩合集【英文标题】:Laravel sum eloquent collection 【发布时间】:2015-03-04 09:50:30 【问题描述】:我如何对已预先加载的数据集求和?
这是我的表结构:
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 | |
+------------+------------------+------+-----+---------------------+----------------+
这些是我的模型/关系:-
class Region extends Eloquent
public function submits()
return $this->hasMany('Submit');
<?php
class Submit extends Eloquent
public function regions()
return $this->belongsTo('Region');
这是我的控制器
public function index()
$regions = Region::with('submits')->get();
return $regions;
//return View::make('pages.index', compact('regions'));
这是返回数据的样子(json格式,我理解$regions在一个雄辩的集合中):-
我不知道如何将“交易”的总和 (4) 发送回视图?
【问题讨论】:
【参考方案1】:$deals = $regions->sum(function ($region)
return $region->submits->sum('deals');
);
【讨论】:
【参考方案2】:你可以显示这个package
$invoices = Region::withSum('submits:deals')->get();
【讨论】:
以上是关于Laravel 和雄辩合集的主要内容,如果未能解决你的问题,请参考以下文章