Related Products are other products that may be needed for the base product or will extend its use. For example, Take laptops as a base product, related products may be a mouse, a keyboard, or a monitor.
If you are a Magento store owner, you must show your customers' related products to serve a better customer experience and increase your sales. Manually doing this task can take forever. Thanks to Magento 2 Automatic Related Products. Using this module, you can display related product items on the product page.
In this blog, we will learn how you can get, add and remove related products in Magento 2.
To get related products in Magento 2, we use Magento\Catalog\Model\Product instance.
<?php ...... public function __construct( $id=44; $relatedProducts = $product->getRelatedProducts(); if (!empty($relatedProducts)) { |
In the above example, we get related product information of product id=”44”.Here we use getRelatedProducts() method to get related products' information. now let’s see how you can add related products in Magento 2
To add related products programmatically we use object manager and use Magento\Catalog\Api\Data\ProductLinkInterface instance.Here We use setSku() method for set base product sku,setLinkedProductSku() method for related product sku and setLinkType() method for set related,upsell or cross sell products.
$productLink = $this->_objectManager->create('Magento\Catalog\Api\Data\ProductLinkInterface') $linkData[] = $productLink; //save product links |
In above example, we have added related products(24-MB03) of base product(24-MB01). Moving on, let’s learn how you can remove related products in Magento 2.
For remove related products in Magento 2, follow below steps:
select * from catalog_product_link_type where code='relation'; |
select entity_id from catalog_product_entity where SKU in ('24-WG02'); |
select * from catalog_product_link where product_id in (44) and link_type_id=1; |
delete from catalog_product_link where product_id in (44) and link_type_id=1; |
Using above blog you can easily understand How to get related products in magento 2? You can also visit our Automatic Related Product extension.If any query in above code implementation,you can contact us or let us know in comment section.
Sign In
Create New Account