Magento 2 – Associate Simple Products to Configurable Products Programmatically

associated-productsconfigurable-productmagento2simple-product

Programmatically:
How to associate simple products to the configurable product without creating configurable product, because it exists.

Best Answer

I found the solution:

Load product configurable by ID:

$associatedProductIds = [2060,2061,2062,2063];//Simple Product ids array
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load(2046); // Load Configurable Product
$product->setAssociatedProductIds($associatedProductIds);
$product->save();

Load product configurable by SKU:

$associatedProductIds = [2060,2061,2062,2063];//Simple Product ids array
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $this->objectManager->create($this->mProduct, null)->getSku('24-WG085_Group'); // Load Configurable Product
$product->setAssociatedProductIds($associatedProductIds);
$product->save();
Related Topic