php - 如何在 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
如果商品相同,如何计算数量和价格?
解决方案
我认为这可以解决您的问题:
$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;
});
推荐阅读
- python - 如何在python中将元组列表转换为固定键目录格式
- linux - Linux 脚本失败
- android - 非法类文件:类模块信息缺少超类型。com.google.code.gson\gson\2.8.6
- python - 将路径名写入文件 (Python)
- java - 为什么标签不显示我的数组元素?
- c++ - 逆向图
- python - discord.py 覆盖 create_text_channel 权限
- ssh - 在 Emacs 中以其他用户身份在其他主机上编辑文件
- javascript - Typerror:对象不是函数或其返回值在反应 16.13.1 中不可迭代
- javascript - 需要帮助保存对字段的 fetch 调用的值