Reputation: 125
This is my sum query, It actually sums up the number of units and a subject price of a specific student.
$subjects = DB::table('subjects')
->join('subjectblocking', 'subjects.subjectcode', '=', 'subjectblocking.subjectcode')
->join('grades', 'subjectblocking.blockcode', '=', 'grades.blockcode')
->select('subjects.numofunit as total_units','subjects.price as total_tuition')
->orWhere(function($query)
{
$query->where('grades.studentid', '=', '2013-F0218')
->where('sem', '=', '1')
->where('sy', '=', '2013-2014');
})
->sum('subjects.numofunit','subjects.price');
return View::make('users.assessment')->with('subjects', $subjects);
This is how I foreach it in blade
@foreach ($subjects as $subject)
{
<tr>
<td>{{$subject->total_units}}</td>
<td>{{$subject->total_tuition}}</td>
</tr>
}
@endforeach
However it tells me that
Invalid argument supplied for foreach()
Upvotes: 2
Views: 3914
Reputation: 81167
This is not how aggregate methods work in Query\Builder
. Check this:
DB::table('a_table')
->sum('a_field'); // returns string, eg. '555'
// or
->count('a_field'); // returns int, eg. 333
The same goes for all aggregate methods.
In order to achieve what you want, you need selectRaw
(DB::raw
) and obviously a groupBy
clause:
DB::table(..)
->selectRaw('sum(a_field) as sum, sum(another_field) as another_sum')
->groupBy('yet_another_field')
->get();
Upvotes: 2