2014-05-15 126 views
0

請需要幫助...添加陣列

$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但仍然不能正常工作。

+0

你想要什麼結果有什麼呢? –

+0

'一月910 345 657''二月345 980 123''三月214 436 989',這樣的事情... – BlackPearl

+0

檢查我的答案,然後 –

回答

0

你必須覆蓋從每月$結果數據數組。你應該使用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(); 
+0

'$ monthValues'將返回'null' – BlackPearl

+0

檢查$個陣列。它應該是null。 –

+0

月陣列包含'payment_month:一月,payment_month:二月,payment_month:March' – BlackPearl

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

能夠解決它時,該網站是隻讀模式,使用'$結果[] = $數據 - >指定者()'。謝謝... – BlackPearl