【问题标题】:Laravel - Query for Aging Report using LaravelLaravel - 使用 Laravel 查询老化报告
【发布时间】:2025-11-26 03:45:01
【问题描述】:

我有想要转换为 Laravel 的 MySQL 查询。

SELECT client_id,
DATEDIFF(CURDATE(), due_date) AS days_past_due,
SUM(IF(days_past_due = 0, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 1 AND 30, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 31 AND 60, amount_due, 0)),
SUM(IF(days_past_due BETWEEN 61 AND 90, amount_due, 0)),
SUM(IF(days_past_due > 90, amount_due, 0))
FROM invoices
GROUP BY client_id

我想使用 Laravel 查询以矩阵格式创建当前、30、60、90 天的老化报告。

例如,

ClientName 当前 1-30 31-60 >90 总计

AAA 3000 1500 4500

BBB 2000 200 2200

总计 3000 3500 200 6700

我想得到这样的报告。当用户输入日期时,它应该检查到期日期。当输入的日期为>due_date时,获取老化天数。

如果老化 agin days 是今天,则获取 netAnmount 并显示在当前列中,

如果相差 1-30 天,那么下一列...等...

如何查询这个?

【问题讨论】:

标签: mysql laravel


【解决方案1】:

我在 Laravel 中使用 subQuery 或许可以帮到你。

$invoice = Invoice::select(\DB::raw('ledgers.id,invoices.invoice_no,invoices.invoice_date,invoices.invoice_due,invoices.invoice_balance,DATEDIFF("'.$request->input('to_date').'", invoices.invoice_date) AS days_past_due'))
                       ->join('quotations','quotations.id','=','invoices.quotation_id')
                        ->join('ledgers','ledgers.id','=','quotations.ledger_id')
                        ->where('invoices.invoice_date','<=',$request->input('to_date'))
                        ->whereNotIn('invoices.status',[1,2]); 
$agingReport = Ledger::select(\DB::raw('a.id,ledgers.name,a.invoice_no,a.invoice_date,a.invoice_due,a.invoice_balance,a.days_past_due,CASE WHEN a.days_past_due =0 then a.invoice_balance else 0 end as month,
                            CASE WHEN a.days_past_due >0 and a.days_past_due <= 30 then a.invoice_balance else 0 end as aging30days,
                            CASE WHEN a.days_past_due >30 and a.days_past_due <= 60 then a.invoice_balance else 0 end as aging60days,
                            CASE WHEN a.days_past_due >60 and a.days_past_due <= 90 then a.invoice_balance else 0 end as aging90days,
                            CASE WHEN a.days_past_due >90 then a.invoice_balance else 0 end as more30days'))
                            ->from(\DB::raw('('.$invoice->toSql().') as a '))
                            ->mergeBindings($invoice->getQuery())
                            ->join('ledgers','ledgers.id','=','a.id')
                            ->get();
return response()->json($agingReport);

【讨论】: