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.
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 .
How can I get it working?
You can try with the sum()
method like:
DB::table('users_stats')
->where('id', '7')
->sum(\DB::raw('logins_sun + logins_mon'));
You can run direct raw sql in laravel with the following way :
$sql = "SELECT SUM(logins_sun + logins_mon) FROM users_stats WHERE id = :ID";
$result = DB::select($sql,['ID'=>7]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With