0

I follow this answer for update related products, It works but it will delete cross sell and upsell products of parent. is this default behavior or did I something wrong?

//For testing load one product

$target=$this->productRepository->getById(501);

//Here I collect related skus list programatically

.........................................
..........................................

$skuLinks = explode(",",$related);
$obj = \Magento\Framework\App\ObjectManager::getInstance();
foreach($skuLinks as $skuLink) {

    $productLink = $obj->create('Magento\Catalog\Api\Data\ProductLinkInterface')
    ->setSku($target->getSku())
    ->setLinkedProductSku($skuLink)
    ->setPosition(1)
    ->setLinkType('related');
    $linkData[] = $productLink;

}

//Set Product Link
$target->setProductLinks($linkData);
$this->productRepository->save($target);

//checking, it only display the related skus, previously it shows related,upsell,crossell
$links=$target->getProductLinks();
foreach($links as $link)
{
    echo $link->getLinkType().' - '.$link->getLinkedProductSku().'<br>';
}         
2

All links will be overwritten, if you call ProductInterface::setLinks method. You can try to add new links in already existed product links array.

Example:

$links = $product->getProductLinks();
$links[] = $newLink;
$product->setProductLinks($links);
$this->productRepository->save($product);
0

The following code works for me. The code inserts product id and the related product ids directly to the database.

 try {
   $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 (".$newRelatedProdId.",".$newProdId.",1)");

                    }
                    catch(Exception $e)
                    {
                        echo 'Duplicate Key'.PHP_EOL;
                    }

Please refer the below links for the further details. https://www.pearlbells.co.uk/programmatically-assign-related-products-magento-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.