【问题标题】:Laravel sum eloquent collectionLaravel 和雄辩合集
【发布时间】: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) 发送回视图?

【问题讨论】:

    标签: sql laravel orm calculated-field


    【解决方案1】:
    $deals = $regions->sum(function ($region) {
        return $region->submits->sum('deals');
    });
    

    【讨论】:

      【解决方案2】:

      你可以显示这个package

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

      【讨论】:

        猜你喜欢
        • 2015-08-15
        • 2013-09-08
        • 2020-08-04
        • 1970-01-01
        • 2020-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-31
        相关资源
        最近更新 更多