/** * {@inheritdoc} */ public function save(\Magento\Catalog\Api\Data\ProductLinkInterface $entity) { $linkedProduct = $this->productRepository->get($entity->getLinkedProductSku()); $product = $this->productRepository->get($entity->getProductSku()); $links = $this->entityCollectionProvider->getCollection($product, $entity->getLinkType()); $extensions = $this->dataObjectProcessor->buildOutputDataArray($entity->getExtensionAttributes(), 'Magento\\Catalog\\Api\\Data\\ProductLinkExtensionInterface'); $extensions = is_array($extensions) ? $extensions : []; $data = $entity->__toArray(); foreach ($extensions as $attributeCode => $attribute) { $data[$attributeCode] = $attribute; } unset($data['extension_attributes']); $data['product_id'] = $linkedProduct->getId(); $links[$linkedProduct->getId()] = $data; $this->linkInitializer->initializeLinks($product, [$entity->getLinkType() => $links]); try { $product->save(); } catch (\Exception $exception) { throw new CouldNotSaveException(__('Invalid data provided for linked products')); } return true; }
/** * {@inheritdoc} */ public function save(\Magento\Catalog\Api\Data\ProductLinkInterface $entity) { $linkedProduct = $this->productRepository->get($entity->getLinkedProductSku()); $product = $this->productRepository->get($entity->getSku()); $links = []; $extensions = $this->dataObjectProcessor->buildOutputDataArray($entity->getExtensionAttributes(), 'Magento\\Catalog\\Api\\Data\\ProductLinkExtensionInterface'); $extensions = is_array($extensions) ? $extensions : []; $data = $entity->__toArray(); foreach ($extensions as $attributeCode => $attribute) { $data[$attributeCode] = $attribute; } unset($data['extension_attributes']); $data['product_id'] = $linkedProduct->getId(); $links[$linkedProduct->getId()] = $data; try { $linkTypesToId = $this->linkTypeProvider->getLinkTypes(); $productData = $this->metadataPool->getHydrator(ProductInterface::class)->extract($product); $this->linkResource->saveProductLinks($productData[$this->metadataPool->getMetadata(ProductInterface::class)->getLinkField()], $links, $linkTypesToId[$entity->getLinkType()]); } catch (\Exception $exception) { throw new CouldNotSaveException(__('Invalid data provided for linked products')); } return true; }