63 $category = $this->categoryRepository->get($categoryId);
75 $link = $this->productLinkFactory->create();
77 ->setPosition(
$product->getData(
'cat_index_position'))
93 $product = $this->getProductRepository()->get($productSku);
94 $assignedCategories = $this->getProductResource()->getCategoryIds(
$product);
95 foreach (array_diff($assignedCategories, $categoryIds) as $categoryId) {
96 $this->getCategoryLinkRepository()->deleteByIds($categoryId, $productSku);
99 foreach (array_diff($categoryIds, $assignedCategories) as $categoryId) {
101 $categoryProductLink = $this->productLinkFactory->create();
102 $categoryProductLink->setSku($productSku);
103 $categoryProductLink->setCategoryId($categoryId);
104 $categoryProductLink->setPosition(0);
105 $this->getCategoryLinkRepository()->save($categoryProductLink);
107 $productCategoryIndexer = $this->getIndexerRegistry()->get(Indexer\Product\Category::INDEXER_ID);
108 if (!$productCategoryIndexer->isScheduled()) {
109 $productCategoryIndexer->reindexRow(
$product->getId());
119 private function getProductRepository()
121 if (
null === $this->productRepository) {
123 ->get(\
Magento\Catalog\Api\ProductRepositoryInterface::class);
133 private function getProductResource()
135 if (
null === $this->productResource) {
147 private function getCategoryLinkRepository()
149 if (
null === $this->categoryLinkRepository) {
151 ->get(\
Magento\Catalog\Api\CategoryLinkRepositoryInterface::class);
161 private function getIndexerRegistry()
163 if (
null === $this->indexerRegistry) {
165 ->get(\
Magento\Framework\Indexer\IndexerRegistry::class);
getAssignedProducts($categoryId)
assignProductToCategories($productSku, array $categoryIds)
__construct(\Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository, \Magento\Catalog\Api\Data\CategoryProductLinkInterfaceFactory $productLinkFactory)