Answer the question
In order to leave comments, you need to log in
Laravel Eloquent: how to sort by sum of values in relation to model?
Hello everyone, there are such models:
Vendor (id, title)
Service (id, vendor_id, type, price)
Vendor hasMany Service
1 | 1 | development | 10
2 | 2 | development | 20
3 | 1 | testing | 20
4 | 1 | testing | 15
5 | 1 | other | 15
Answer the question
In order to leave comments, you need to log in
It is possible like this:
$vendors = Vendor::with(['services' => function($query) {
$query->selectRaw('SUM(price) as sum, vendor_id, type')
->groupBy('vendor_id')
->groupBy('type')
->orderBy('sum', 'desc');
}])
->selectRaw('*, (SELECT SUM(price) FROM service WHERE service.vendor_id = vendor.id) as sum')
->orderBy('sum', 'desc')
->get();
@foreach($vendors as $vendor)
<p><strong>{{ $vendor->title }} - сумма: {{ $vendor->sum }}</strong></p>
@foreach($vendor->services as $service)
<p>--- {{$service->type}}: {{ $service->sum }}</p>
@endforeach
@endforeach
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question