1

I've created a grouped product programetically. And want too map associate products to it. I tried the following code which didn't work. first way:

$gProduct->setGroupedLinkData(array($id1,$id2));

second way:

$gProduct->setAssociatedProducts(array($id1,$id2));

Any suggestions will be appreciated.

Thanks in advance.

2

Your associated products array should be like this

$data = array();
$data[$simpleId] = array('qty' => 9, 'position' => 0);
$data[$simple2Id] = array('qty' => 3, 'position' => 0);
$grouped->setGroupedLinkData($data);
$grouped->save();
  • But by default added with status = 0, disabled, how can I change it? – Lucas D.A.W. Jan 22 '18 at 8:41
0

Please use the following code that worked for me.

 $associated = array();
$position = 0;

foreach($childrenIds as $productId) {

    $position++;
    $productRepository = $objectManager->create('\Magento\Catalog\Api\ProductRepositoryInterface');
    $linkedProduct = $productRepository->getById($productId);
    $productLink = $objectManager->create('Magento\Catalog\Api\Data\ProductLinkInterface');
    $productLink->setSku($product->getSku())
        ->setLinkType('associated')
        ->setLinkedProductSku($linkedProduct->getSku())
        ->setLinkedProductType($linkedProduct->getTypeId())
        ->setPosition($position)
        ->getExtensionAttributes()
        ->setQty(1);

    $associated[] = $productLink;


}


$product->setProductLinks($associated);
$product->save();
0

The following code also work but that is not the best way.

 $q = $objectManager->get('\Magento\Framework\App\ResourceConnection');
 $q->getConnection('core_write')->query("insert into catalog_product_link (linked_product_id, product_id,link_type_id) values (".$newSimpleProdId.",".$grpProdId.",2)");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.