Laravel 查询多个关系

Laravel query for multiple relationships

我需要计算发票状态 - 未清、已付、逾期。

我的table结构:

invoices:
- id
- custome_id
- total_amount
...

invoice_payments
- id
- invoice_id
- amount_received
...

正在尝试:

$records->whereHas('invoice', function($query) use ($val) {
    $query->whereHas('invoicePayments', function($_query){
        $_query->sum('amount_received');
    });
});

我关心的是获取发票的状态 - 如果 invoice->sum('amount') > invoice->invoicePayment->sum('amount_received').

我想借助 whereHas 函数而不是数据库原始查询来完成它。请建议方法。

此查询适用于分页:

Invoice::where('total_amount', '<=', function($query) {
    $query->selectRaw('SUM(amount_received)')
        ->from('invoice_payments')
        ->where('invoice_id', DB::raw('invoices.id'));
})->paginate();