Try below code:
$obj = \Magento\Framework\App\ObjectManager::getInstance();
/** @var \Magento\Catalog\Model\Product $product */
$productObject = $obj->get('Magento\Catalog\Model\Product');
$product = $productObject->loadByAttribute('sku', 'Test Test');
$linkDataAll = [];
$skuLinks = "0012365,test1233,789456";
$skuLinks = explode(",",$skuLinks);
foreach($skuLinks as $skuLink) {
//check first that the product exist
$linkedProduct = $productObject->loadByAttribute("sku",$skuLink);
if($linkedProduct) {
/** @var \Magento\Catalog\Api\Data\ProductLinkInterface $productLinks */
$productLinks = $obj->create('Magento\Catalog\Api\Data\ProductLinkInterface');
$linkData = $productLinks //Magento\Catalog\Api\Data\ProductLinkInterface
->setSku($product->getSku())
->setLinkedProductSku($skuLink)
->setLinkType("related");
$linkDataAll[] = $linkData;
}
}
if($linkDataAll) {
print(count($linkDataAll)); //gives 3
$product->setProductLinks($linkDataAll);
}
$product->save();
dont use **objectmanager** this code just for reference
0 comments:
Post a Comment