在循环Laravel中添加数组

时间:2014-05-15 03:09:30

标签: php laravel-4

请帮助......

$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);

上面的查询工作正常,我在数据库表中有January, February and March个月,但它只返回March的记录。

我试过results[]=$data但仍然无法工作。

2 个答案:

答案 0 :(得分:1)

我认为这就是你所需要的:

$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"}, ... ]

答案 1 :(得分:0)

您已从每个月结果覆盖$ data数组。你应该使用whereIn如下。

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