简体   繁体   中英

get order products categories in laravel

I have four tables Order , Category , Product , Order_Product

each product belongs to a category each order has many products

i save the order products in order_product table,

now in orderResource i want to have number of order->products in each category so OrderResource should have

data 
[
{
 category_name: 'something',
productsCount: 3,
},
{
category_name: 'somethingelse',
productsCount: 2
}
]

how to do so?

So you want to get products from an order, and group the products by category and count the number of products in a category.

$orders = Order::with(['products' => function($query) {
    $query->groupBy('category_id')
        ->select(DB::raw('count(*) AS productsCount'), 'category_id')
        ->with('category');
}])
->get();

foreach($orders as $order) {
    foreach($order->products as $product) {
        $product->productsCount;
        $product->category->name;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM