Laravel createMany() 和 saveMany() 函数执行多个插入查询而不是 1 个

Laravel createMany() and saveMany() functions doing multiple insert queries instead of 1

提问人:Leon Kardaš 提问时间:3/24/2023 最后编辑:aynberLeon Kardaš 更新时间:3/24/2023 访问量:334

问:

我正在使用 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

如果需要更多代码/解释,我很乐意提供

php mysql laravel 雄辩 的 sql-insert

评论

0赞 aynber 3/24/2023
你在循环中做,然后你用 再次保存它。选择一个或另一个。new OrderProductorderProducts()->saveMany($order_products);
0赞 Leon Kardaš 3/24/2023
@aynber我不是在做链接中描述的一样的事情吗?$order_products 不应该最终变成一个数组,里面装满了与数据库无关的内存分配对象吗?
0赞 aynber 3/24/2023
嗯,你是对的。您是收到重复的行,还是只是担心它单独保存一行? 使用 foreach 循环来保存每个模型,而不是进行批量插入。saveMany
0赞 Leon Kardaš 3/24/2023
我不知道它是这样运作的。但是,是的,我没有重复行的问题,我只需要一个批量插入saveMany
0赞 aynber 3/24/2023
我不记得是否会进行批量插入。你可以试试看insert()

答: 暂无答案