我有一个Laravel应用程序。我正在尝试计算列的平衡和平衡。你能帮我解决一下如何为此编写SQL。
+---------+----------+--------+----------+----------+------------+
| pay_id | username | income | outgoings| balance | date |
+---------+----------+--------+----------+----------+------------+
| 1 | john | 1000 | | 1000 | 00.00.2016 |
| 2 | jack | | 500 | 500 | 00.00.2016 |
| 3 | john | 1500 | | 2000 | 00.00.2016 |
| 4 | bill | | 1000 | 1000 | 00.00.2016 |
+---------+----------+--------+----------+----------+------------+
2500 1500
答案 0 :(得分:0)
如果您正在使用Eloquent:
Model::where('username', 'john')->sum('balance');
https://laravel.com/docs/5.3/eloquent#retrieving-single-models
答案 1 :(得分:0)
如果您想要对多列进行求和,那么您必须向我们DB::raw
$data = Model::get([
DB::raw('SUM(income) AS total_income'),
DB::raw('SUM(outgoings) AS total_outgoings'),
DB::raw('SUM(balance) AS total_balance')
]);
dd($data);
或者
$data = Model::select(
DB::raw('SUM(income) AS total_income'),
DB::raw('SUM(outgoings) AS total_outgoings'),
DB::raw('SUM(balance) AS total_balance')
)
->get();
dd($data);