简体   繁体   English

如何使用 Laravel Query Builder 获取两个不同列的总和?

[英]How to get sum of two different columns with Laravel Query Builder?

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 1034 but the Laravel Query is returning only the last value 587.0 .它应该返回1034但 Laravel 查询只返回最后一个值587.0

How can I get it working?我怎样才能让它工作?

sum is an aggregate function and only takes one argument. sum是一个聚合函数,只接受一个参数。 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() ).在您的情况下,查询仅返回一行,因此总和只是该列的值(传递给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.可能有一些更好的方法来做到这一点,但我认为您应该能够使用原始表达式来返回两列的总和。

$stats = DB::table('users_stats')
             ->select(DB::raw('logins_sun + logins_mon'))
             ->where('id', '=', '7');

You can try with the sum() method like:您可以尝试使用sum()方法,例如:

DB::table('users_stats')
    ->where('id', '7')
    ->sum(\DB::raw('logins_sun + logins_mon'));

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;
});

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]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM