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:
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.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;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
ObjectManagerdirectly (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

