简体   繁体   English

获取 laravel 中的订单产品类别

[英]get order products categories in laravel

I have four tables Order , Category , Product , Order_Product我有四个表OrderCategoryProductOrder_Product

each product belongs to a category each order has many products每个产品属于一个类别每个订单都有很多产品

i save the order products in order_product table,我将订单产品保存在order_product表中,

now in orderResource i want to have number of order->products in each category so OrderResource should have现在在 orderResource 我想在每个类别中有一些 order->products 所以 OrderResource 应该有

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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