Stefanos
Stefanos

Reputation: 37

How to sum two columns in Laravel 5.6

I have a SQL query and I want to convert it to eloquent. My query that I know that it works is:

SELECT DISTICT(excavatorId), SUM(times_loaded), SUM(litres) FROM daily GROUP BY excavatorId;

and it returns the following result:

+-------------+-------------------+-------------+
| excavatorId | sum(times_loaded) | sum(litres) |
+-------------+-------------------+-------------+
|          55 |               179 |         168 |
|          60 |                50 |          50 |
+-------------+-------------------+-------------+

Now in Laravel i try the following:

$result = DB::table('daily as d')
                ->select([
                    'excavatorId',
                    'times_loaded',
                    'litres'
                ])
              ->groupBy('excavatorId')
              ->where('date', $request->input('date'))
              ->sum('d.times_loaded', 'd.litres');

This query only returns a string that has the value "179" only. What is the correct way to do this in Laravel and have the result of the SQL query?

Upvotes: 1

Views: 7371

Answers (1)

Murat Tutumlu
Murat Tutumlu

Reputation: 780

Use DB::raw() to make database operations without retrieving all data.

    $result = DB::table('daily')
          ->select([
                'excavatorId',
                DB::raw("SUM(times_loaded) as total_times_loaded"),
                DB::raw("SUM(litres) as total_liters"),
            ])
          ->groupBy('excavatorId')
          ->where('date', $request->input('date'))
          ->get();

You don't need to use daily as d as you are not joining two tables so that you may need a table reference.

Please find the reference here

Upvotes: 3

Related Questions