首页 > 解决方案 > 如何在 laravel 中获取订单商品销售报告?

问题描述

我正在尝试获取上个月的订单项目报告。这是我的表结构

orders
    id - integer
    amount- double

order_items (pivot table)
    id - integer
    order_id - foreign
    item_id - foreign
    quantity
    price

这是我的Item模型

public function orders()
{
    return $this->belongsToMany(Order::class, 'order_items', 'item_id',  'order_id')
                ->withPivot('quantity', 'price');
}

这是我的Order模型

public function items()
{
    return $this->belongsToMany(Item::class, 'order_items', 'order_id', 'item_id')
                ->withPivot('quantity', 'price')
                ->withTimestamps();
}

这是我的控制器,我从那里得到了上个月的所有订单

$orders = Order::with('items')
               ->whereMonth('created_at', '=', Carbon::now()->subMonth()->month)
               ->get();

在刀片中的 foreach 循环之后,

@foreach ($orders as $order)
  <ul>
    @foreach($order->items as $item)
      <li>
        {{ $item->name }}, {{ $item->pivot->quantity }}, {{ $item->pivot->price }}
      </li>
    @endforeach
  </ul>
  <hr>
@endforeach

我得到这样的数据

Item Name  Quantity Price
Item A         20    600
Item A         15    400
Item A          5    200
Item B          5    100
Item B          5    100


但我不想在这一行显示相同的项目,我想这样显示

Item Name  Quantity Price
Item A         40    1200
Item B         10    200

如果商品相同,如何计算数量和价格?

标签: phpmysqllaraveleloquent

解决方案


我认为这可以解决您的问题:

$orders = Order::with('items')
            ->whereMonth('created_at', '=', Carbon::now()->subMonth()->month)
            ->get();

$orders->transform(function($order){
    $itemsArray = [];
    $order['items'] = $order['items']->groupBy('name')->map(function ($item) use ($itemsArray){
        array_push($itemsArray, [
            'name' => $item[0]['name'], 
            'qty' => $item->sum('qty'),
            'price' => $item->sum('price')
        ]);
        return $itemsArray[0];
    })->values();
    return $order;
});

推荐阅读