无法将简单产品与可配置产品magento 2关联

时间:2018-07-12 22:04:25

标签: magento magento2 configurable-product

我正在尝试通过代码将一些简单产品与已经创建的可配置产品相​​关联。使用我创建的控制台命令。这段代码创建了可配置产品,但未能关联简单产品。

    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>');

}

当我检查数据库时,他们将不会显示相关的产品,而在后端,我将看不到产品。我尝试过手动映射具有正确关联的产品,但仍然没有运气

0 个答案:

没有答案
相关问题