Magento 2 Programmatically Update Product Categories

categorymagento2magento2.3productprogrammatically

How can I remove existing and assign new categories to product programmatically in magento 2 while updating product data.

 <?php

 $newCategoryIds = array(5,6);

 $existingProductId = 25;

 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

 $_product = $objectManager->create('Magento\Catalog\Model\Product')->load($existingProductId);

 $_product->setName('New name xyz'); // Name of Product

 $existing = $_product->getCategoryIds(); 

 print_r($existing);// Return existing assign categories like Array(3,4)

 $_product->setCategoryIds([]); // Want to remove existing categories so i can assign updated categories but its not working

 $_product->save();

 $_product->setCategoryIds($newCategoryIds); // It's also not remove existing categories.

 $_product->save();

Best Answer

This worked for me

\Magento\Catalog\Api\CategoryLinkManagementInterface $categoryLinkManagementInterface
   /**
     * Assign product to category.
     *
     * @param \Magento\Catalog\Model\Product $product
     * @param array                          $categoryIds
     *
     * @return void
     */
    public function assignProductToCategory($product, $categoryIds = [])
    {
        if (!empty($categoryIds)) {
            $this->categoryLinkManagementInterface->assignProductToCategories(
                $product->getSku(),
                $categoryIds
            );
        }
    }

So new array wipes out existing values.