Skip to content

Magento2 Add multiple configurable items into cart with same parent product

Magento2 multiply the qty of first item if add two configurable item into cart programmatically with same parent product.

$items = [
        [
            'product_id'=>'47',
            'parent_id'=>'62',
            'qty'=>1
        ],
        [
            'product_id'=>'48',
            'parent_id'=>'62',
            'qty'=>1
        ]
    ];

foreach($items as $item){
    if(isset($item['parent_id']) && !empty($item['parent_id'])){
        //$quote = $checkoutSession->getQuote();
        $product = $productModel->getById($item['parent_id']);
        $childProduct = $productModel->getById($item['product_id']);
        $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
        $options = [];
        foreach($productAttributeOptions as $option){
            $options[$option['attribute_id']] =  $childProduct->getData($option['attribute_code']);
        }

        $objParam = new MagentoFrameworkDataObject(
            [
                'product' => $product->getId(),
                'qty' => $item['qty'],
                'super_attribute' => $options
            ]
        );        
        $quote->addProduct($product, $objParam);
    } else {
        $product= $productModel->getById($item['product_id']);
        $quote->addProduct($product, intval($item['qty']));
    }
}
$quote->save(); 

Any help will be appreciated, Thank you