【问题标题】:how to get order item sales report in laravel?如何在 laravel 中获取订单商品销售报告?
【发布时间】:2021-10-01 16:20:55
【问题描述】:

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

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

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

【问题讨论】:

  • 使用 GROUP BY 项。你需要在mysql上查询吗?
  • 你能用 groupBy 提供 MySQL 查询吗?

标签: php mysql laravel eloquent


【解决方案1】:

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

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

【讨论】:

  • 它不起作用
猜你喜欢
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2023-01-05
  • 1970-01-01
  • 2021-07-17
  • 2012-11-25
  • 1970-01-01
相关资源
最近更新 更多