Laravel总和eloquent合集

Laravel sum eloquent collection

如何对已预加载的数据集求和?

这是我的 table 结构:

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 格式,我理解 eloquent 集合中的 $regions):-

我不知道如何将 'deals' (4) 的总和发送回视图?

$deals = $regions->sum(function ($region) {
    return $region->submits->sum('deals');
});

你可以展示这个package

$invoices = Region::withSum('submits:deals')->get();