laravel - Eloquent 连接和求和
问题描述
我有 2 个表,并希望获得一个查询,该查询从表“项目”中获取所有列,并根据字段“类型”从表“发票”中获取几个总和。
projects
+----+--------+------+--------+
| ID | Address| Date | Other |
+----+--------+------+--------+
| 1 | demo | date | other |
| 2 | demo2 | date2| other2 |
invoices
+----+---------+-----+--------+
| ID | proj_id | type| amount |
+--------------+-----+--------+
| 1 | 1 | a | 10 |
| 2 | 1 | a | 20 |
| 3 | 1 | b | 10 |
| 4 | 1 | b | 15 |
| 5 | 1 | c | 5 |
| 6 | 2 | a | 30 |
| 7 | 2 | a | 5 |
| 8 | 2 | b | 30 |
| 9 | 2 | c | 5 |
| 10 | 2 | c | 30 |
使用 Laravel Eloquent 我希望能够获得:
+----+---------+------+-------+---+---+---+
| ID | Address | Date | Other | a | b | c |
+----+---------+------+-------+---+---+---+
| 1 | demo | date | other |30 |25 | 5 |
| 2 | demo2 | date2| other2|35 |30 |35 |
我被总和部分困住了,实际上是整个事情!
到目前为止,我有:
$projects = DB::table('projects')
->leftJoin('invoices', 'projects.id', '=', 'invoices.project_id')
->select('projects.*', 'invoices.*')
->get();
这显然不是很远!任何帮助将不胜感激!
解决方案
您需要一个基本的数据透视查询。最简单的方法可能是通过原始选择:
$sql = "projects.*, ";
$sql .= "sum(case when invoices.type = 'a' then invoices.amount end) as a, ";
$sql .= "sum(case when invoices.type = 'b' then invoices.amount end) as b, ";
$sql .= "sum(case when invoices.type = 'c' then invoices.amount end) as c";
$projects = DB::table('projects')
->select(DB::raw($sql))
->leftJoin('invoices', 'projects.id', '=', 'invoices.project_id')
->groupBy('project.id')
->get();
这应该对应于以下原始 MySQL 查询:
SELECT
p.*,
SUM(CASE WHEN i.type = 'a' THEN i.amount END) AS a,
SUM(CASE WHEN i.type = 'b' THEN i.amount END) AS b,
SUM(CASE WHEN i.type = 'c' THEN i.amount END) AS c
FROM project p
LEFT JOIN invoices I
ON p.id = i.project_id
GROUP BY
p.id;
推荐阅读
- swift - 在 Perform Segue 上传递参数返回 nil
- c++ - 在 Windows 中通过 Eclipse 使用 CMake 的 LibTorch:终止退出值 390
- swift - 无法获取 SavedPost
- python - 如何根据屏幕分辨率适配使用 PyQt5 开发的 GUI?
- api - 如何在 Zabbix API 中搜索主机组
- javascript - Unicode 代理对和 String.fromCodePoint() — JavaScript
- java - 如何将我的多行输出转换为 3x4
- php - PHP - 如何在换行符之前使用“>”删除换行符
- python - 在创建的文件中添加文本
- php - HTTP:状态 405:url:'http://mydashboard/mybi/gateway.php''