当前位置: 首页 > 面试题库 >

Laravel sum eloquent collection

阴礼骞
2023-03-14
问题内容

我该如何总结一个渴望加载的数据集?

这是我的表结构:

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):-

原始json

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


问题答案:

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



 类似资料:

相关阅读

相关文章

相关问答