1

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?

1

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();
        }
  • Thanks! It returns PHP Fatal error: Uncaught TypeError: Argument 1 passed to Magento\Catalog\Model\Product\Interceptor::setProductLinks() must be of the type array or null, object given – Coen Ponsen Aug 16 '18 at 21:13
  • I have updated the code , check the EDIT section – Vivek Kumar Aug 16 '18 at 21:31
  • Yeah, I saw that in the other post, just tried it and no result.... Count function returns 8 but still only showing the last item – Coen Ponsen Aug 16 '18 at 21:34
  • I have edited more code in edit , please check again – Vivek Kumar Aug 16 '18 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.