A brief compilation of Laravel

How can I summarize a dataset that has been loaded?

This is my table structure:

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 |                |
+------------+------------------+------+-----+---------------------+----------------+

These are my models / relationships: -

class Region extends Eloquent {

  public function submits()
  {
    return $this->hasMany('Submit');
  }

}

<?php

class Submit extends Eloquent {

  public function regions()
  {
    return $this->belongsTo('Region');
  }

}

This is my controller

  public function index()
  {
    $regions = Region::with('submits')->get();

    return $regions;
    //return View::make('pages.index', compact('regions'));
  }

Here's what the returned data looks like (in json format, I understand $ regions in an eloquent collection): -

raw json

I can’t understand how I can send the sum of “deals” (4) back to the view?

+4
source share
1 answer
$deals = $regions->sum(function ($region) {
    return $region->submits->sum('deals');
});
+6
source

Source: https://habr.com/ru/post/1570187/


All Articles