是否需要避免查询 N+1 问题
请问一下,$item->product
这个地方是否需要先在上面load一下再执行下面的循环,否则会出现N+1问题吧?
// Laravel 会默认执行监听器的 handle 方法,触发的事件会作为 handle 方法的参数
public function handle(OrderPaid $event)
{
// 从事件对象中取出对应的订单
$order = $event->getOrder();
// 循环遍历订单的商品
foreach ($order->items as $item) {
$product = $item->product;
// 计算对应商品的销量
$soldCount = OrderItem::query()
->where('product_id', $product->id)
->whereHas('order', function ($query) {
$query->whereNotNull('paid_at'); // 关联的订单状态是已支付
})->sum('amount');
// 更新商品销量
$product->update([
'sold_count' => $soldCount,
]);
}
}
推荐文章: