You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Magento代码创建多商品订单异常:多商品合并为单一商品且数量累加

问题分析与解决方案

Hey there, let's figure out why all your products are merging into one line item with summed quantities.

The root cause here is reusing the same Product model instance across your loop. When you inject \Magento\Catalog\Model\Product via the constructor, you're getting a single stateful object. Every time you call $this->_product->load($item->getProductId()), you're just overwriting the data in that same object instead of creating a new product entry. When you pass this reused object to $cart->addProduct(), Magento sees it as the same product every time and adds the quantities together instead of creating separate line items.

Fix Steps:

  1. Switch to using ProductFactory instead of Product model
    Instead of injecting \Magento\Catalog\Model\Product, inject \Magento\Catalog\Model\ProductFactory—this lets you create a fresh Product instance for each item in your loop.

  2. Update your constructor
    Modify the constructor parameters and assignments:

    // Replace this line in constructor params
    // \Magento\Catalog\Model\Product $product,
    \Magento\Catalog\Model\ProductFactory $productFactory,
    
    // Add this assignment in the constructor body
    $this->_productFactory = $productFactory;
    
  3. Update the product loop
    Create a new Product instance for each item:

    //add items in quote
    foreach($productInfo as $item){
        // Create a fresh Product instance every time
        $product = $this->_productFactory->create()->load($item->getProductId());
        $product->setPrice($item->getPrice());
        $cart->addProduct(
            $product,
            intval($item->getQty())
        );
    }
    

Extra Tips:

  • Avoid using ObjectManager directly (like you did with $objectManager = \Magento\Framework\App\ObjectManager::getInstance();). Stick to dependency injection—it's Magento's recommended practice, makes code more maintainable, and easier to test.
  • After adding all products, make sure to call $cart->save() to persist the quote changes (your current code might handle this later, but it's good to double-check).

内容的提问来源于stack exchange,提问作者Dhara Parmar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:23:37