雄辩的连接和总和

时间:2018-05-29 03:28:17

标签: laravel eloquent

我有2个表,希望得到一个查询,该查询从表'projects'中获取所有列,并根据字段'type'获取表'发票'中的几个总和。

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

这显然不是很远!任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您需要一个基本的透视查询。到这里最简单的方法可能是通过原始选择:

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;

这应该对应于以下原始MySQL查询:

{{1}}