Need a script where current existing products needs to unlink and link to other categories. let me know the process also

有帮助吗?

解决方案

Following is the code you will use in order to assign and unassign categories from product

 //Object Manager instance
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

//Product repository interface
 $productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');

//Load Product - assuming we have product id only
 $product = $objectManager->create('Magento\Catalog\Model\Product')->load( $product_id );

$category_id = '34'; //Replace category id here

$product->setCategoryIds( array($category_id) ); //It accepts array so we can add multiple category ids.

try {
 $productRepository->save($product);
 } catch (\Exception $e) {
 // Handle error
 }

I hope this will help

其他提示

Use below code to assign:

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

$CategoryLinkRepository = $objectManager->get('\Magento\Catalog\Api\CategoryLinkManagementInterface');

$category_ids = array('101','102');
$sku = '24-MB01';

$CategoryLinkRepository->assignProductToCategories($sku, $category_ids);

And below to remove:

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

  $CategoryLinkRepository = $objectManager- >get('\Magento\Catalog\Model\CategoryLinkRepository');

  $categoryId = 101;
  $sku = '24-MB01';

  $CategoryLinkRepository->deleteByIds($categoryId,$sku);
许可以下: CC-BY-SA归因
scroll top