首页 > 解决方案 > 如何在 Laravel 5.6 中对两列求和

问题描述

我有一个 SQL 查询,我想将其转换为 eloquent。我知道它有效的查询是:

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

它返回以下结果:

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

现在在 Laravel 我尝试以下方法:

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

此查询仅返回值“179”的字符串。在 Laravel 中执行此操作并获得 SQL 查询结果的正确方法是什么?

标签: mysqllaravel-5eloquent

解决方案


使用 DB::raw() 在不检索所有数据的情况下进行数据库操作。

    $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();

您不需要使用daily as d,因为您没有加入两个表,因此您可能需要表引用。

请在此处找到参考


推荐阅读