【发布时间】: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