如何使用 Laravel Query Builder 获取两个不同列的总和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44509697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get sum of two different columns with Laravel Query Builder?
提问by Vinny
I'm trying to get the sum of two different columns using Laravel query builder, the plain SQL Query below works just fine, but I can't get it to work with the Laravel Query.
我正在尝试使用 Laravel 查询构建器获取两个不同列的总和,下面的普通 SQL 查询工作正常,但我无法使用 Laravel 查询。
SELECT SUM(logins_sun + logins_mon) FROM users_stats WHERE id = 7; // returns: 1034
Here's what I have tried.
这是我尝试过的。
$stats = DB::table('users_stats')->where('id', '=', '7')->sum('logins_sun', '+', 'logins_mon'); // returns: 587.0
And here is my DB structure.
这是我的数据库结构。
+----+------------+------------+
| id | logins_sun | logins_mon |
+----+------------+------------+
| 7 | 587 | 447 |
+----+------------+------------+
It was supposed to return 1034but the Laravel Query is returning only the last value 587.0.
它应该返回1034但 Laravel 查询只返回最后一个值587.0。
How can I get it working?
我怎样才能让它工作?
回答by Don't Panic
sum
is an aggregate function and only takes one argument. It will sum the values of each row in a column. In your case, the query only returns one row, so the sum is just the value of that one column (the first argument passed to sum()
). There may be some better way to do it, but I think you should be able to use a raw expression to return the sum of the two columns.
sum
是一个聚合函数,只接受一个参数。它将对列中每一行的值求和。在您的情况下,查询仅返回一行,因此总和只是该列的值(传递给 的第一个参数sum()
)。可能有一些更好的方法来做到这一点,但我认为您应该能够使用原始表达式来返回两列的总和。
$stats = DB::table('users_stats')
->select(DB::raw('logins_sun + logins_mon'))
->where('id', '=', '7');
回答by Anwar Khan
You can try with the sum()
method like:
您可以尝试使用以下sum()
方法:
DB::table('users_stats')
->where('id', '7')
->sum(\DB::raw('logins_sun + logins_mon'));
回答by Anwar Khan
Try passing a callback to the sum() and do the addition there like:
尝试将回调传递给 sum() 并在那里进行添加,例如:
$stats = DB::table('users_stats')->where('id', '=', '7')->sum(function ($row) {
return $row->logins_sun + $row->logins_mon;
});
回答by Nazmul Hasan
You can run direct raw sql in laravel with the following way :
您可以通过以下方式在 laravel 中直接运行原始 sql:
$sql = "SELECT SUM(logins_sun + logins_mon) FROM users_stats WHERE id = :ID";
$result = DB::select($sql,['ID'=>7]);