D
D
dk-web2016-03-11 09:51:35
MySQL
dk-web, 2016-03-11 09:51:35

How to make multilevel grouping of table values?

There is a simple table
source | type | price
1 | cash | 100
1 | cash | 200
1 | non-cash | 150
2 | cash | 150
2 |clearing | 400
2 |clearing| 500
I want to get a summary table of sums with double grouping.
array (2)
- source 1 array (2)
-- cash 300
-- non-cash 150
- source 2 array (2)
-- cash 150
-- non-cash 900
, etc.

return DB::table('orders')
                     ->select('source','type', DB::raw('sum(price) as total_price'))
                     ->whereBetween('created_at', array(Carbon::yesterday()->startOfDay(), Carbon::yesterday()->endOfDay()))
                     ->groupBy('source','type')
                     // ->groupBy('type')
                     ->get();

UPD:
Now I'm getting...
array:3 [▼
  0 => {#185 ▼
    +"source": "1"
    +"type": "Безнал"
    +"total_price": 433.0
    +"total_cash": 433.0
  }
  1 => {#189 ▼
    +"source": "1"
    +"type": "Нал"
    +"total_price": 661.0
    +"total_cash": 350.0
  }
  2 => {#190 ▼
    +"source": "2"
    +"type": "Нал"
    +"total_price": 455.0
    +"total_cash": 0.0
  }
]

accordingly, I would need to group arrays 1 and 2...
UPD2:
Here's what I managed to do.... the same request, but applied the collection...
$sum=collect($this->orders->forUserSum($request->user()));
$grouped = $sum->groupBy('source');
$grouped->toArray();
dd($grouped);

Result.
Collection {#177 ▼
  #items: array:2 [▼
    "1" => Collection {#189 ▼
      #items: array:2 [▼
        0 => {#191 ▼
          +"source": "1"
          +"type": "Безнал"
          +"total_price": 433.0
          +"total_cash": 433.0
        }
        1 => {#192 ▼
          +"source": "1"
          +"type": "Нал"
          +"total_price": 661.0
          +"total_cash": 350.0
        }
      ]
    }
    "2" => Collection {#185 ▼
      #items: array:1 [▼
        0 => {#193 ▼
          +"source": "2"
          +"type": "Нал"
          +"total_price": 455.0
          +"total_cash": 0.0
        }
      ]
    }
  ]
}

strong farm? "straighter" maybe?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrzej Wielski, 2016-03-11
@dk-web

Passing to view:

DB::table('orders')
     ->select('source','type', 'price')
     ->whereBetween('created_at', array(Carbon::yesterday()->startOfDay(), Carbon::yesterday()->endOfDay()))
     ->get()->groupBy('source');

All output is implemented on the blade:
<table>
   <tr>
      <th>Source</th>
      <th>Нал</th>
      <th>Безнал</th>
   </tr>
   @foreach($rows as $source => $row)
  <tr>
     <td>{{ $source }}</td>
     <td>{{ $row->where('type', 'нал')->sum('price') }}</td>
     <td>{{ $row->where('type', 'безнал')->sum('price') }}</td>
         </tr>
    @endforeach
   </table>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question