Example 7. GROUP BY + ORDER BY: Multiple Columns

Example 7. GROUP BY + ORDER BY: Multiple Columns

2024-10-15 وقت القراءه : 2 دقائق

"في هذا المثال، سنوضح لك كيفية تجميع البيانات حسب عمود وترتيبها حسب عدة أعمدة.

على سبيل المثال، نريد تجميع طلباتنا حسب الشهر الذي تم إنشاؤها فيه ومن ثم ترتيبها حسب عدد الطلبات الإجمالي:"

للحصول على البيانات كما بالصوره أعلاه

$orders = Order::selectRaw(
    'month(orders.order_time) as month, sum(order_product.quantity) as total_quantity, sum(orders.total) as order_total, count(*) as total_orders, products.name as product_name'
)
    ->join('order_product', 'order_product.order_id', '=', 'orders.id')
    ->join('products', 'order_product.product_id', '=', 'products.id')
    // Group by Month first, then by product name
    ->groupByRaw('month(orders.order_time), product_name')
    // Order by month, then by total orders
    ->orderBy('month')
    ->orderBy('total_orders', 'desc')
    ->get();

شرح الكود

$orders = Order::selectRaw(
    'month(orders.order_time) as month, sum(order_product.quantity) as total_quantity, sum(orders.total) as order_total, count(*) as total_orders, products.name as product_name'
)

selectRaw: يسمح بإدخال استعلام SQL خام. يقوم هذا الاستعلام بتحديد:

  • month(orders.order_time) as month: يستخرج الشهر من تاريخ الطلب.
  • sum(order_product.quantity) as total_quantity: يحسب مجموع الكميات لكل منتج في الطلبات.
  • sum(orders.total) as order_total: يحسب مجموع المبالغ الكلية للطلبات.
  • count(*) as total_orders: يحسب عدد الطلبات.
  • products.name as product_name: يستخرج اسم المنتج المرتبط بكل طلب.


->join('order_product', 'order_product.order_id', '=', 'orders.id')
->join('products', 'order_product.product_id', '=', 'products.id')

يربط الجدول order_product بجدول orders عبر order_id.

يربط الجدول products بجدول order_product عبر product_id. هذا يسمح بجلب اسم المنتج لكل طلب.

->groupByRaw('month(orders.order_time), product_name')

يقوم بتجميع البيانات أولاً بناءً على الشهر، ثم بناءً على اسم المنتج. هذا يفيد في التحليل الشهري للطلبات حسب المنتج.

->orderBy('month')
->orderBy('total_orders', 'desc')

يرتب النتائج أولاً حسب الشهر.

ثم يرتب النتائج حسب total_orders بترتيب تنازلي، مما يعني أن الشهور التي بها أكبر عدد من الطلبات تظهر أولاً.


عرض البيانات في blade

<table class="table table-striped table-bordered">
    <thead>
    <tr>
        <th>Date</th>
        <th>Product</th>
        <th>Total</th>
        <th>Total Items</th>
        <th>Total Orders</th>
    </tr>
    </thead>
    <tbody>
    @foreach ($orders as $order)
        <tr>
            <td>{{ $order->month }}</td>
            <td>{{ $order->product_name }}</td>
            <td>${{ number_format($order->order_total, 2) }}</td>
            <td>{{ $order->total_quantity }}</td>
            <td>{{ $order->total_orders }}</td>
        </tr>
    @endforeach
    </tbody>
</table>


إضافة تعليق
Loading...