Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

laravel

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?

like image 397
Vinny Avatar asked Jun 12 '17 22:06

Vinny


2 Answers

You can try with the sum() method like:

DB::table('users_stats')
    ->where('id', '7')
    ->sum(\DB::raw('logins_sun + logins_mon'));
like image 143
Anwar Khan Avatar answered Oct 24 '22 05:10

Anwar Khan


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]);
like image 23
Nazmul Hasan Avatar answered Oct 24 '22 06:10

Nazmul Hasan