Answer the question
In order to leave comments, you need to log in
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();
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
}
]
$sum=collect($this->orders->forUserSum($request->user()));
$grouped = $sum->groupBy('source');
$grouped->toArray();
dd($grouped);
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
}
]
}
]
}
Answer the question
In order to leave comments, you need to log in
Passing to view:
DB::table('orders')
->select('source','type', 'price')
->whereBetween('created_at', array(Carbon::yesterday()->startOfDay(), Carbon::yesterday()->endOfDay()))
->get()->groupBy('source');
<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 questionAsk a Question
731 491 924 answers to any question