Laravel中许多列的总和

时间:2018-05-04 05:22:10

标签: php laravel

我有这个功能,帮助我找到两行的总和并得到总成本的输出所以我想再次得到输出的总和(总成本)。

public function getUsageData(Request $request)
{
    $start_date = $request->get('start_date');
    $end_date = $request->get('end_date');
    $particulars =DB::table('particulars')
        ->join('reqs', 'particulars.particular_id', "=", 'reqs.particular_id')
        ->whereBetween('date_issued', [$start_date, $end_date])
        ->select('particulars.item_name','particulars.unit','particulars.price','reqs.quantity_issued',
            DB::raw('sum(particulars.price*reqs.quantity_issued)AS total_cost'))
        ->groupBy('particulars.particular_id')
        ->get();       
}

我得到两行的总和Total费用。我想在底部获得总成本列的总和,以便在不计算的情况下使用户易于理解。

1 个答案:

答案 0 :(得分:0)

尝试使用此代码,请分享表格结构

$particulars =DB::table('particulars as A')
    ->leftjoin('reqs as B', function ($join) {
        $join->on('A.particular_id', '=', 'B.particular_id');
    })
    ->whereBetween('A.date_issued', [$start_date, $end_date]) // i have taken date issued from table particulars as you have not mentioned else you can change A.date_issued as B.date_issued .
    ->select('A.item_name','A.unit','A.price','B.quantity_issued',DB::raw('sum(A.price*B.quantity_issued) as total_cost'))
    ->groupBy('A.particular_id')
    ->get();