提问人:Leon Kardaš 提问时间:3/24/2023 最后编辑:aynberLeon Kardaš 更新时间:3/24/2023 访问量:334
Laravel createMany() 和 saveMany() 函数执行多个插入查询而不是 1 个
Laravel createMany() and saveMany() functions doing multiple insert queries instead of 1
问:
我正在使用 Laravel 9 和 PHP 8.1.0。我正在尝试通过 HasMany/Belong to 关系保存订单项目(一个订单有多个 OrderProducts)。虽然我使用的是 saveMany 方法,但我遇到了 N+1 问题。代码的作用是从$calculation获取数据,这些数据不存储在数据库中,而是作为模型实例上的属性。然后通过 foreach,我遍历每个产品并创建一个“本地”OrderProduct 对象。然后,我想使用 saveMany 使用一个查询来保存它。
我尝试切换到 createMany() 方法,但我得到了相同的确切结果。我怀疑我可能多次运行 saveMany(),所以我记录了它,不,它只显示一个。我试着把它喂给chatGPT,但它也没有帮助
代码:
发生问题的功能:
public function createOrderItems(Order $calculation, Order $order): void
{
$order_products = [];
foreach ($calculation->getProducts() as $product) {
$order_products[] = new OrderProduct([
'product_id' => $product->product_id,
'quantity' => $product->quantity,
'price_with_pdv' => $product->price_with_pdv,
'price_without_pdv' => $product->price_without_pdv,
'weight' => $product->weight,
]);
}
$order->orderProducts()->saveMany($order_products);
}
如何调用该函数$this->createOrderItems($calculation, $order);
orderProducts() 关系(在订单模型上):
public function orderProducts(): HasMany
{
return $this->hasMany(OrderProduct::class);
}
这是望远镜日志:
insert into `order_products` (`product_id`, `quantity`, `price_with_pdv`, `price_without_pdv`, `weight`... 0.33ms
insert into `order_products` (`product_id`, `quantity`, `price_with_pdv`, `price_without_pdv`, `weight`... 0.34ms
insert into `order_products` (`product_id`, `quantity`, `price_with_pdv`, `price_without_pdv`, `weight`... 0.50ms
insert into `order_products` (`product_id`, `quantity`, `price_with_pdv`, `price_without_pdv`, `weight`... 0.30ms
insert into `order_products` (`product_id`, `quantity`, `price_with_pdv`, `price_without_pdv`, `weight`... 0.45ms
如果需要更多代码/解释,我很乐意提供
答: 暂无答案
评论
new OrderProduct
orderProducts()->saveMany($order_products);
saveMany
saveMany
insert()