我想获得一个数组/集合,如下所示
---------------------------------------------------------
| age range | invoice count | total amount |
---------------------------------------------------------
| overdue > 60 days | 200 | 20450 |
| overdue 30 to 60 days | 33 | 3600 |
| due today | 60 | 5000 |
| due next 7 days | 200 | 2550 |
| due next 8 to 30 days | 50 | 500 |
| due after 30 days | 150 | 2432 |
---------------------------------------------------------
来自具有发票明细列的表(id,user_id,amount,due_date,status,created_at,updated_at),我正在尝试以下内容:
$invoice_age = InvoiceDetail::where('user_id', Auth::user()->id)
->select('due_date', DB::raw('(to_days(due_date) - to_days(now())) AS age'))
->whereIn('status', ['created', 'viewed])
->orderBy('age')
->get()->toArray();
这给出了一个年龄数组,但我无法弄清楚我如何得到group by age
,count
和amount total
的发票,就像我在上面的数组表中所示
更新
以下是帮助我的SQL查询,但我需要编写 eloquent or fluent
查询。
SELECT
x.invoice_age_range,
count(*) invoice_count,
sum(invd_invoicetotal) invoice_amount
FROM
(SELECT
CASE
WHEN (to_days(due_date) BETWEEN (to_days(now()) - 7) AND to_days(now()))
THEN 'overdue_7_days'
WHEN (to_days(due_date) BETWEEN (to_days(now()) - 15) AND (to_days(now()) - 8))
THEN 'overdue_8_to_15_days'
WHEN (to_days(due_date) BETWEEN (to_days(now()) - 30) AND (to_days(now()) - 15))
THEN 'overdue_15_to_30_days'
WHEN (to_days(due_date) < (to_days(now()) - 30))
THEN 'overdue_30_days'
WHEN (to_days(due_date) BETWEEN to_days(now()) AND (to_days(now()) + 7))
THEN 'due_in_7_days'
WHEN (to_days(due_date) BETWEEN (to_days(now()) + 7) AND (to_days(now()) + 15))
THEN 'due_in_15_days'
WHEN (to_days(due_date) BETWEEN (to_days(now()) + 15) AND (to_days(now()) + 30))
THEN 'due_in_30_days'
WHEN (to_days(due_date) > (to_days(now()) + 30))
THEN 'due_after_1_month'
END invoice_age,
amount
FROM invoice_details
WHERE user_id = 2
AND status IN ('viewed', 'created')
) x
GROUP BY x.invoice_age_range;
谢谢,
Karmendra
(我在集合方面的思维方面并不擅长,因此我很讨厌SQL查询)
答案 0 :(得分:0)
为此你可能想要使用原始查询并从雄辩的范围中放入
DB::table( DB::raw("your case query here")
->select ()
->gropby()