簡體   English   中英

Laravel eloquent 組 eloquent 以小時間隔記錄左連接

[英]Laravel eloquent group eloquent records in hourinterval with Left join

我正在使用 laravel v8,我有兩個結構如下的表:

訂單

ID 全部的 created_at
1 100 2022-01-01 11:00:05
2 300 2022-01-01 15:00:05
.. .. ...

order_items

ID order_id product_id 數量
1 1 2 1
2 1 4 3
.. .. .. ..

我想生成一份報告,其中包含一天內每小時(59 分 59 秒)間隔的訂單摘要,例如:

日期 時間 總訂單 總訂單項目數量 總訂單金額
2020 年 1 月 1 日 00:00 - 00:59 0 0 0
2020 年 1 月 1 日 01:00 - 01:59 0 0 0
2020 年 1 月 1 日 02:00 - 02:59 0 0 0
2020 年 1 月 1 日 03:00 - 03:59 1 2 80
2020 年 1 月 1 日 04:00 - 04:59 3 10 500
2020 年 1 月 1 日 05:00 - 0:59 0 0 0
………… ..................... ... ... ...
2020 年 1 月 1 日 21:00 - 21:59 5 18 1020
2020 年 1 月 1 日 22:00 - 22:59 1 5 210
2020 年 1 月 1 日 23:00 - 0:59 0 0 0

目前我需要像這樣的每個間隔 select 然后執行 foreach 循環來匯總間隔的數據:

$orders = DB::table('orders')
            ->select(
                [
                    DB::RAW('orders.total as total'),
                    DB::RAW('order_items.quantity as quantity')
                ]
            )
            ->leftJoin ('order_items. AS order_items.', function ($query) {
                $query->on('order_items..order_id', '=', 'orders.id'); 
            })
            ->whereBetween('orders.created_at',[date('Y-m-d 00:00:00'),date('Y-m-d 00:59:59')]) 
             ->get();

$totalOrder = $orders->count();
$totalQuantity = 0;
$totalAmount = 0;
foreach($orders as $order){
   $totalQuantity += $order->quantity;
   $totalAmount += $order->total;
}

$data['00:00 - 00:59'] = [
  'total_order' => $totalOrder,
  'total_quantity' => $totalQuantity,
  'total_amount' => $totalAmount,
];

該解決方案有效,但不是很有效,我如何運行單個查詢數據庫來實現這種結果?

使用別名和group by

$orders = DB::table('orders')
    ->select(
        [
            DB::RAW('left(orders.created_at,13) as hour'),
            DB::RAW('sum(orders.total) as total'),
            DB::RAW('sum(order_items.quantity) as quantity')
        ]
    )
    ->leftJoin('order_items', 'order_items.order_id', '=', 'orders.id')
    ->groupBy('hour')
    ->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM