Magento 2: Upsell programmaticly add products only adds last item
-
22-01-2021 - |
Question
I am trying to add upsell products automaticly with the Magento\Catalog\Api\Data\ProductLinkInterfaceFactory
class, I added following code:
EDIT CODE IS UPDATED WITH AN WORKING EXAMPLE
$i = 100;
foreach ($collection as $item) {
$productLink = $this->productLinkInterfaceFactory->create();
$productLink->setSku($product->getSku())
->setLinkedProductSku($item->getSku())
->setPosition($i++)
->setLinkType('upsell');
$linkData[] = $productLink;
}
if ($linkData) {
$product->setProductLinks($linkData);
$product->save();
}
I tried solving it with the following similar post: link
But no result. It only adds the last product, anybody knows how to add all products?
Solution
Remove $linkData[] = $productLink;
and instead do $product->setProductLinks($linkData);
, I think there is problem with the scope of $linkdata[]
.
Modified code ;
$productLink = $this->productLink;
foreach ($collection as $item) {
$productLink->setSku($product->getSku())
->setLinkedProductSku($item->getSku())
->setPosition($i++)
->setLinkType('upsell');
}
if ($linkData) {
$product->setProductLinks($productLink);
$product->save();
}
EDIT ;
Try your code only but define the $linkData
beforehand (scope outside the loop too) , also we need to create new object of Magento\Catalog\Api\Data\ProductLinkInterface
for each loop iteration
$linkData = [];
foreach ($collection as $item) {
$productLink = $this->productLink->create(); // we need to create new object for each loop iteration
$productLink->setSku($product->getSku())
->setLinkedProductSku($item->getSku())
->setPosition($i++)
->setLinkType('upsell');
$linkData[] = $productLink;
}
if ($linkData) {
$product->setProductLinks($linkData);
$product->save();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange