I have some troubles with assigning simple or virtual products to a configurable product in Magento 2 programmatically.

The code I use is already from a Magento.StackExchange issue but it is not working for me and am really confused already. Through my testing, I use hardcoded variables. Simple products (future variants and parent) are created manually. my code just runs the createConfigurable() method once. Attribute code 93 is for color and 193 for size. The Result is that I get a configurable product (parent) but not assigned with the variations.

public function createConfigurable(){
    $attributeSetId = 9;
    $parentId = 161;
    $associatedProductIds = array(157,158);//Simple Product ids array
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->create('Magento\Catalog\Model\Product')->load($parentId); // Load Configurable Product
    $attributeModel = $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable\Attribute');
    $position = 0;
    $attributes = array(93,139); // Super Attribute Ids Used To Create Configurable Product(list of supper attribute ids what ever belong to that the attribute set under which the configurable product is)

    foreach ($attributes as $attributeId) {
        $data = array('attribute_id' => $attributeId, 'product_id' => $parentId, 'position' => $position);
    $objectManager->create('Magento\ConfigurableProduct\Model\Product\Type\Configurable')->setUsedProductAttributeIds($attributes, $product);
    $product->setAssociatedProductIds($associatedProductIds);// Setting Associated Products

hope someone has ideas to solve this issue!

thank you



Browse other questions tagged or ask your own question.