[英]Calculate sum using Laravel Query Builder by applying groupBy on Table1.id but without soft deleted rows on Table2?
I want to get all the purchases and their sums and also I don't want to add the amount if payments.deleted_at is not null. 我要获取所有购买及其金额,并且如果payments.deleted_at不为null,我也不想添加金额。
Here are the tables 这是桌子
purchases 购买
id | name
1 | Gamerzone Book
2 | Recipe Book
3 | EngineX Book
payments 付款方式
id | purchase_id | amount | deleted_at
1 1 100 2015-06-12 11:00:00
2 2 50 NULL
2 2 10 NULL
Code 码
$query = DB::table('purchases')
->select(['purchases.*',
DB::raw("IFNULL(sum(payments.amount),0) as total")
])
->leftJoin('payments','payments.purchase_id','=','purchases.id')
->whereNull('payments.deleted_at')
->groupBy('purchases.id')->get();
When I run the code below the 1st result is not included. 当我运行下面的代码时,第一个结果不包括在内。 Result
结果
id | name | total
2 | Recipe Book 60
3 | EngineX Book 0
I know why It is not included but the problem is if I remove whereNull('payments.deleted_at') that particular row in payments will also add to the sum.How should I solve this ?? 我知道为什么它不包括在内,但问题是如果我删除whereNull('payments.deleted_at')支付中的特定行也将加到总和中,我该如何解决?
Expected Result 预期结果
id | name | total
1 | Gamerzone Book 0
2 | Recipe Book 60
3 | EngineX Book 0
In this case your join condition should looks like this: 在这种情况下,您的加入条件应如下所示:
ON (payments.booking_id = purchases.id AND payments.deleted_at IS NOT NULL) 开启(payments.booking_id = purchases.id和payments.deleted_at不为空)
And it is not about WHERE (according to your SELECT). 它与WHERE无关(根据您的SELECT)。 You should use join-closure like this:
您应该像这样使用join-closure:
$query = DB::table('purchases')
->select(['purchases.*', DB::raw("IFNULL(sum(payments.amount),0) as total")])
->leftJoin('payments', function($join) {
$join->on('payments.booking_id', '=', 'purchases.id');
$join->on('payments.deleted_at', 'IS', DB::raw('NOT NULL'));
})
->groupBy('purchases.id')->get();
Just replace 只需更换
->leftJoin('payments','payments.booking_id','=','purchases.id')
with 与
->leftJoin('payments', function($join) {
$join->on('payments.booking_id', '=', 'purchases.id');
$join->on('payments.deleted_at', 'IS', DB::raw('NOT NULL'));
})
and remove this: 并删除此:
->whereNull('payments.deleted_at')
it should help. 它应该有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.