2

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()

3
  • This means that there is an error in your query. Commented Dec 7, 2014 at 15:22
  • @LorenzMeyer well ofc. but how can i foreach a sum in blade? Commented Dec 7, 2014 at 16:50
  • There's no problem with foreach. The problem is in your query. $subjects is false instead of an array. Commented Dec 7, 2014 at 17:43

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.