Magento 2 – import product relation links programmatically
In this tutorial I show you ow to import product relation links programmatically. For this you need at least two products. One product is our base product, the other is a related product, so we want to link it to our base product.
Magento 2 – import product relation links programmatically
Magento offers you to create links between products, in your Magento backend (1 and 2) you will see the following predefined tabs on your product detail site:
Magento offers you to store different link types. These types are:
- Related Products
that are other products that may be needed for our base product or will extend its use. Think of a laptop as base product, related products may be a mouse, a keyboard or a monitor. - Up-sells
are similar products with better options and higher prices. Think of a laptop with more RAM or a higher CPU speed. - Cross-sells
that are other products a customer may wants to buy. A good choice is to display products that other customers bought. It is simply a technique to sell more products for each individual order.
Related products
We can add unlimited products as related products to a base product. For this we create an array with all products links:
1 2 3 4 5 6 7 | $productLink = $this->_objectManager->create('Magento\Catalog\Api\Data\ProductLinkInterface') ->setSku($sourceMaterial) ->setLinkedProductSku($targetMaterial) //->setPosition(1) ->setLinkType($linkType); $linkData[] = $productLink; |
For this we add Magento\Catalog\Api\Data\ProductLinkInterface models to an array. We have to set SKU and LinkType. If you want to add more than one related product you can also set a position to sort your list. Possible link types are:
- related
- upsell
- crosssell
Now we can save this array of product links for base product:
1 2 3 4 5 | //save product links $product = $this->_objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface')->get($sourceMaterial); if($product) { $product->setProductLinks($linkData)->save(); } |
We now save our product by Magento\Catalog\Api\ProductRepositoryInterface. There is a function called setProductLinks. You will set our previously created array as param.
Conclusion
It is possible to mass import product relation links programmatically. There are three possible types of links.