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


//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')
    $linkData[] = $productLink;


//Set Product Link

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

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


$links = $product->getProductLinks();
$links[] = $newLink;
| improve this answer | |
  • it make sense. I will test... :-) – Bilal Usean Feb 4 '17 at 16:02
  • you provide answer for add new product links, however for update/replace we need to preserve crosssell and upsell alone after that add related skus, finally overwrite. :-) – Bilal Usean Feb 6 '17 at 6:38
  • Please answer on this magento.stackexchange.com/questions/233321/… – Jugal Kishor Jul 13 '18 at 10:17
  • not working, getting this error Call to a member function getLinkType() on array in /var/www/html/rectorsealwork/vendor/magento/module-catalog/Model/ProductRepository.php:451 – Yogesh May 12 at 14:29

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/

| improve this answer | |

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.