I am trying to update products programatically and I'm having issues with the related/upsell section.
It updates only with the last product sku. So if I am trying to link 3 products with a parent one as in the example below, only the last one will appear in the related section for product parent_sku
.
$linkDataAll = [];
$skuLinks = "9780500420584,9780500544679,9780500650936";
$skuLinks = explode(",",$skuLinks);
foreach($skuLinks as $skuLink) {
//check first that the product exist
$linkedProduct = $this->productFactory->create()->loadByAttribute("sku",$skuLink);
if($linkedProduct) {
$linkData = $this->productLinks //Magento\Catalog\Api\Data\ProductLinkInterface
->setSku("parent_sku")
->setLinkedProductSku($skuLink)
->setLinkType("related");
$linkDataAll[] = $linkData;
}
}
if($linkDataAll) {
print(count($linkDataAll)); //gives 3
$product->setProductLinks($linkDataAll);
}
$product->save();