Laravel 5.7-将两列相乘并加到最终总和

时间:2018-12-11 22:25:20

标签: php mysql laravel

我有两个表-学生表和产品表。

当我在表格中列出学生名单时,我需要查看已支付的总金额(总和),但不幸的是,看起来结果是正确的总和,但要乘以行数。

学生桌

+----+----------+
| id |   name   |
+----+----------+
|  1 | Jonathan |
|  2 | Bob      |
+----+----------+

产品表

+----+------------+-------+----------+
| id | student_id | money | quantity |
+----+------------+-------+----------+
|  1 |          1 |  1000 |        2 |
|  2 |          1 |  2000 |        1 |
|  3 |          2 |   500 |        5 |
|  4 |          2 |  3000 |        1 |
+----+------------+-------+----------+

付款表

+----+-------+------------+
| id | money | student_id |
+----+-------+------------+
|  1 |  5000 |          1 |
|  2 |  2000 |          1 |
|  3 |  2500 |          2 |
|  4 |  2500 |          2 |
+----+-------+------------+

从理论上讲,我的查询输出应该为:

+-------------+----------+----------------+----------------+
| id          |   name   | payments_total | products_total |
+-------------+----------+----------------+----------------+
|           1 | Jonathan |  4000          |           7000 |
|           2 | Bob      |  5500          |          10000 |
+-------------+----------+----------------+----------------+

我尝试过的事情

        $teamStudents = DB::table('students')->where('students.team', $team)->orderBy('first_name', 'ASC') 
                                ->join('products', 'students.id', '=', 'products.student_id')
                                ->join('payments', 'students.id', '=', 'payments.student_id')
                                ->select('students.first_name AS first_name', 'students.last_name AS last_name', 'students.created_at AS created_at', DB::raw('SUM(products.money * products.amount) AS products_total'), DB::raw('SUM(payments.money) AS payments_total'), 'students.id AS id')
                                ->groupBy('students.id')
                                ->get();

除了由于某些原因返回的“ payments_total”不正确且乘以行数的事实外,它不返回任何错误。

所以我的问题是: 我该如何解决?我做错了什么?我已经搜寻了一个小时,没有结果。

我的查询是一个问题还是我的设置方式,如果是这样,正确的解决方案是什么?

2 个答案:

答案 0 :(得分:1)

通过您的编辑,我能够解决您遇到的问题,但是在您进行的编辑中,您使用了一些我没有数据的东西,例如<v-checkbox label="Check1" value="Check1" v-model="Check1" ></v-checkbox> <v-checkbox label="Check2" value="Check2" v-model="Check2" ></v-checkbox> $teamfirst_name个学生中。但是无论如何,这是您的问题的解决方案,您必须使用子查询才能解决此问题:

last_name

我不确定从技术上讲我是否会正确,但是问题是因为您使用了多个联接,所以如果不使用子查询,结果就是结果加倍。

答案 1 :(得分:0)

在这种情况下,无需加入,无论如何您都不会使用它。

$teamStudents = DB::table('students')
    ->select('id, name')
    ->selectRaw('select sum(money) from payments where student_id = students.id as payments_total')
    ->selectRaw('select sum(money) from products where student_id = students.id as products_total')
    ->orderBy('name')
    ->get();