mysql - 如何在 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 查询结果的正确方法是什么?
解决方案
使用 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
,因为您没有加入两个表,因此您可能需要表引用。
请在此处找到参考
推荐阅读
- php - 收不到邮件 (PHP)
- python - JSON.loads 编码问题 - 文件与字符串
- android - 从 StartActivity(ActivityFlags.NewTask) 返回时未调用 BroadcastReceiver OnReceive
- python - Scipy.Minimize,如何在目标函数和约束之间共享相同的对象?
- javascript - 使用正则表达式在查询中查找重复参数
- docker - 有没有办法在集群中使用多个 docker 注册表代理?
- google-cloud-platform - 生成 GCP 资源清单
- database - 对仅通过多对多关系不同的表使用专业化吗?
- javascript - 过滤以搜索数据库中的项目
- python - 在 pydatatable 数据框中使用 f 表达式选择必填字段的建议