John Davidson

php - how to group by the relation entity in laravel

0 comments
Message:


i have 2 models order and city and each order has one city now what i want to do is to show the user how many orders per each city he has . and the result for example would be some thing like below :


Illuminate\Support\Collection {#2220 ▼
#items: array:17 [▼
"new-york" => 80
"city-number2" => 20
"city-number3" => 10
"city-number4" => 5
]
}

what i have tried so far is to work with the laravels withcount on order like below :


        $orders = Order::withCount('orders')->where('shop_id', $shop->id)->get();


but no luck with it because it returns the count of all cities not each city individually .
thanks in advance



My Answer:
"City A": 5,
"City B": 3,
"City C": 2
}

To achieve this in Laravel, you can use the `groupBy` method along with the `count` method. Here's an example code snippet:

php
$orders = Order::all();
$ordersPerCity = $orders->groupBy('city_id')->map(function ($orders) {
return $orders->count();
});

dd($ordersPerCity);


In this code snippet, we first fetch all orders and then group them by the `city_id` attribute. We then use the `map` method to count the number of orders for each city. Finally, we use `dd` to dump and die the result.

Rate this post

4 of 5 based on 3938 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us