【发布时间】:2018-12-13 11:01:24
【问题描述】:
我在我的 Laravel 5.6 应用程序中设置了以下关系。
Purchase belongs to many Invoice
Invoice belongs to many Purchase
Invoice belongs to many Payment
Payment belongs to many Invoice
这些关系是使用数据透视表建立的。
我想仅查找通过发票支付为 0 的购买。
在我的测试中,我有 一个 购买,我附上了 两张 发票到该购买,并且我附上了 一个 付款到每个那些发票。一笔付款金额为 100,另一笔付款金额为 0。
为了通过我的测试,查询应该不返回任何结果,但是,它并没有这样做,它始终返回我创建的购买。
这是我写的查询:
Purchase::whereHas('invoices.payments', function ($q) {
return $q->where('amount', '<=', 0);
})->get();
我也试过了:
Purchase::whereDoesntHave('invoices.payments', function ($q) {
return $q->where('amount', '>', 0);
})->get();
我在这里做错了吗?我是否误解了 WhereHas 的功能?
任何帮助将不胜感激,谢谢。
【问题讨论】:
-
>我只想找到通过发票支付为 0 的购买。>一笔付款的金额为 100,另一笔的金额为 0。>它始终退回我的购买创建。看起来不错?
-
您是否要获取只有零金额付款而金额> 0的付款?
-
我想要购买,通过发票,只有 0 的付款。如果该购买有任何与它相关的超过 0 的付款,我不想要购买。
-
第二个查询看起来正确。可以分享一下
dd(Purchase::whereDoesntHave('invoices.payments', function ($q) { return $q->where('amount', '>', 0); })->toSql()) -
好的,感谢您的帮助:
select * from `purchases` where exists (select * from `invoices` inner join `invoice_purchase` on `invoices`.`id` = `invoice_purchase`.`invoice_id` where `purchases`.`id` = `invoice_purchase`.`purchase_id` and not exists (select * from `payments` inner join `invoice_payment` on `payments`.`id` = `invoice_payment`.`payment_id` where `invoices`.`id` = `invoice_payment`.`invoice_id` and `amount` > ? and `payments`.`deleted_at` is null) and `invoices`.`deleted_at` is null) and `purchases`.`deleted_at` is null
标签: laravel eloquent query-builder