korbax
12/29/2017 - 9:42 AM

Set related products programatically Magento 2

Set related products programatically Magento 2

$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();