Laravel 求和 Eloquent 集合。

11

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

这是我的表结构:

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 是 Eloquent 集合):

raw json

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

2个回答

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

0
你可以展示这个
$invoices = Region::withSum('submits:deals')->get();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接