Laravel DB查询与计数
问题描述:
我有一个查询,我需要使用计数和有一个正常的查询。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以及计算总计
答
这是正确的查询
$affdata = DB::table('Affiliates')->select(DB::raw('sum(total) as total'), 'AffID', 'user_id')
->whereRaw('CompletedDate >= curdate()')
->groupBy('AffID')
->orderBy('user_id', 'ASC')
->get();
答
更新您的查询。
$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();