显示具有相同user_id的数据并将sum_unit列加总

时间:2019-07-07 14:40:07

标签: laravel

表格

--------------------------------------------------
user_id                           amount_unit
--------------------------------------------------
82ei3j3r2ijwkjewk32893e                3
2y8r42t8f432929420234y8                2
2y8r42t8f432929420234y8                4
82ei3j3r2ijwkjewk32893e                2
--------------------------------------------------

结果

--------------------------------------------------
user_id                           amount_unit
--------------------------------------------------
82ei3j3r2ijwkjewk32893e                5
2y8r42t8f432929420234y8                6
--------------------------------------------------

我也想显示user_id。我尝试在控制器上仅显示amount_unit的总和,

$data = BankDeposit::with('user')->selectRaw('SUM(amount_unit) as au')
    ->groupBy('user_id')->get();

foreach ($data as $value) {
    echo $value;
}

1 个答案:

答案 0 :(得分:0)

您也应该将user_id传递给selectRaw()

$data = BankDeposit::with('user')->selectRaw('SUM(amount_unit) as au, user_id')
           ->groupBy('user_id')->get();