Hello I am using given below code to add simple product in configurable product.but it is not properly working.
$productId = 1; // Configurable Product Id
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->create('MagentoCatalogModelProduct')->load($productId); // Load Configurable Product
$attributeModel = $objectManager->create('MagentoConfigurableProductModelProductTypeConfigurableAttribute');
$position = 0;
$attributes = array(134, 135); // Super Attribute Ids Used To Create Configurable Product
$associatedProductIds = array(2,4,5,6); //Product Ids Of Associated Products
foreach ($attributes as $attributeId) {
$data = array('attribute_id' => $attributeId, 'product_id' => $productId, 'position' => $position);
$position++;
$attributeModel->setData($data)->save();
}
$product->setTypeId('configurable'); // Setting Product Type As Configurable
$product->setAffectConfigurableProductAttributes(4);
$objectManager->create('MagentoConfigurableProductModelProductTypeConfigurable')->setUsedProductAttributeIds($attributes, $product);
$product->setNewVariationsAttributeSetId(4); // Setting Attribute Set Id
$product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products
$product->setCanSaveConfigurableAttributes(true);
$product->save();