Reputation: 2775
Please need help...
$months = Records::select('payment_month')
->distinct()->where('payment_year',$year)
->where('company_id',$company_id)->get();
foreach ($months as $month) {
$data = Records::select(
DB::raw('SUM(record_db.credits) as credits'),
DB::raw('SUM(record_db.amount) as amount'),
DB::raw('SUM(record_db.totalamount) as totalamt'), 'record_db.payment_month')
->where('record_db.company_id','=',$company_id)
->where('record_db.payment_month','=',$month->payment_month)
->where('record_db.payment_year','=',$year)
->first();
}
return Response::json($data);
The above query works fine and I have the month of January, February and March
in the database table but it only returns the records of March
.
I tried results[]=$data
but still don't work.
Upvotes: 0
Views: 120
Reputation: 81167
I think this is what you need:
$data = Records::select(
'payment_month',
DB::raw('SUM(record_db.credits) as credits'),
DB::raw('SUM(record_db.amount) as amount'),
DB::raw('SUM(record_db.totalamount) as totalamt')
)->where('company_id', '=', $company_id)
->where('payment_year', '=', $year)
->groupBy('payment_month')
->orderBy('payment_month')
->get();
// then
$data->toJson(); // returns something like:
[{"payment_month":"January","credits":"123","amount":"456","totalamt":"789"}, ... ]
Upvotes: 1
Reputation: 4330
You had override $data array from every month result. You should use whereIn as follows.
$months = Records::select('payment_month')
->distinct()->where('payment_year', $year)
->where('company_id',$company_id)->get();
$monthValues = array();
foreach ($months as $month) {
$monthValues[] = $month->payment_month;
}
$data = Records::select(
DB::raw('SUM(record_db.credits) as credits'),
DB::raw('SUM(record_db.amount) as amount'),
DB::raw('SUM(record_db.totalamount) as totalamt'), 'record_db.payment_month')
->where('record_db.company_id','=',$company_id)
->whereIn('record_db.payment_month', $monthValues)
->where('record_db.payment_year','=',$year)
->first();
Upvotes: 0