Add new related products programmatically

This blog post describes how how you can add related products in Magento 2. Other guides that I’ve found did not work, overwrote existing related products or used pure API methods to attempt to do it.

Depending on the scope where you will be running this code, I’ve noticed that in custom command (bootstrapping Magento 2) you need to set the area code to “adminhtml”.

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');

Let’s get started. First off, we need to load our product in some way. I’m using Object Manager to illustrate this.

$productModel = $this->objectManager->get('Magento\Catalog\Model\Product')
    ->load($productId);

We need to have a look at existing product links (related, upsell, crosssell) and keep that. We’re receiving an array of objects, so new relationships can be added onto that array.

$productLinks = $productModel->getProductLinks();

Next, we need to create the link between two products. In this code I’m assuming that the $relatedProduct variable is loaded with a product model.

$newLink = $this->objectManager->create('Magento\Catalog\Model\ProductLink\Link')
    ->setSku($productModel->getSku())
    ->setLinkedProductSku($relatedProduct->getSku())
    ->setPosition(0)
    ->setLinkType('related');

$productLinks[] = $newLink;

That’s it. The array now contains the old links and also the new link. All we need to do right now is to update the product model and save it.

$productModel
    ->setProductLinks($productLinks)
    ->save();

Another issue I ran into, was that the product had no linked products, even though it was added through admin. This was due to missing store_id when loading the product in a certain scope.

Hope this helps anyone else looking for connecting products!