2016-06-14 226 views
1

我有一個查詢,我需要使用計數和有一個正常的查詢。Laravel DB查詢與計數

普通

select sum(total) as Total,AffID,user_id from Affiliates 
group by AffID order by user_id ASC 

而且隨後

foreach($result_array as $row) 
{ 
    echo $row['total']."<br/>"; 
    echo $row['AffID']."<br/>"; 
    echo $row['user_id ']."<br/>"; 
} 

在Laravel我曾嘗試

$affdata = DB::select('Affiliates') 
     ->whereRaw('CompletedDate >= curdate()') 
     ->groupBy('AffID') 
     ->orderBy('user_id', 'ASC') 
     ->sum('total'); 
     ->get(); 
foreach($affdata as $row) 
{ 
    echo $row->AffID ."<br>"; 
    echo $row->total ."<br>"; 
} 

但似乎拋出了一個錯誤。因爲我需要回顯AFFID以及計算總計

回答

0

這是正確的查詢

$affdata = DB::table('Affiliates')->select(DB::raw('sum(total) as total'), 'AffID', 'user_id') 
      ->whereRaw('CompletedDate >= curdate()') 
      ->groupBy('AffID') 
      ->orderBy('user_id', 'ASC') 
      ->get(); 
1

更新您的查詢。

$affdata = DB::table('Affiliates')->select(DB::raw('sum(total) as total'), 'AffID', 'user_id')) 
      ->whereRaw('CompletedDate >= curdate()') 
      ->groupBy('AffID') 
      ->orderBy('user_id', 'ASC') 
      ->sum('total'); 
      ->get();