I am trying to associate some simple products with an already created configurable product via code. using a console command that i created. This code creates the configurable product but fails to associate the simple products.
protected function execute(
InputInterface $input,
OutputInterface $output
) {
$output->writeln('<info>Starting process...<info>');
$output->writeln('');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$configurable_product = $objectManager->create('\Magento\Catalog\Model\Product');
$configurable_product->setSku('A2008'); // set sku
$configurable_product->setName('SOLUCION S. NORMAL 0.9%'); // set name
$configurable_product->setAttributeSetId(4);
$configurable_product->setStatus(1);
$configurable_product->setTypeId('configurable');
$configurable_product->setPrice(0);
$configurable_product->setWebsiteIds(array(1)); // set website
$configurable_product->setCategoryIds(167); // set category
$configurable_product->setHasOptions(1);
// super attribute
$presentation = 136;
$configurable_product->getTypeInstance()->setUsedProductAttributeIds(array($presentation), $configurable_product); //attribute ID of attribute 'size_general' in my store
$configurable_product->setCanSaveConfigurableAttributes(true);
$configurableProductsData = array();
$configurableProductsData['3974'] = array( //['920'] = id of a simple product associated with this configurable
'0' => array(
'label' => 'presentation', //attribute label
'attribute_id' => 136, //attribute ID of attribute 'color' in my store
'value_index' => 2139 //value of 'Green' index of the attribute 'color'
)
);
$configurable_product->setConfigurableProductsData($configurableProductsData);
try {
$configurable_product->save();
} catch (Exception $ex) {
echo '<pre>';
print_r($ex->getMessage());
exit;
}
$productId = $configurable_product->getId();
// assign simple product ids
// $associatedProductIds = array(3974, );
/* try{
$configurable_product = $objectManager->create('Magento\Catalog\Model\Product')->load($productId); // Load Configurable Product
// $configurable_product->setAssociatedProductIds($associatedProductIds); // Setting Associated Products
$configurable_product->setCanSaveConfigurableAttributes(true);
$configurable_product->save();
} catch (Exception $e) {
echo "<pre>";
print_r($e->getMessage());
exit;
}*/
$output->writeln('<info>Done<info>');
}