I am creating a frontend from for Sellers to add/edit their product on website, product adding/editing is working perfect. Now I have to assign that product to a category

Almost on every article and blog there is one proper solution to assign product to a category:

//Removing previous categories
$previousCategoryIds = $product->getCategoryIds();
foreach($previousCategoryIds as $k=>$previousCategoryId){

//Assigning new categories

The code is fine, but I am getting this error:

Fatal error: Uncaught Error: Call to undefined method Magento\Catalog\Model\ResourceModel\Category\Flat::saveAttribute() in ...vendor/magento/module-catalog-url-rewrite/Observer/CategoryUrlPathAutogeneratorObserver.php:96

I have searched this error and found the cause of this error:

The problem is, category link repository and link management is only for backend, and I am trying to use it on frontend scope that's why it is causing this error.

I have also tried this:


But above code appending categories, not replacing previous categories.

Can you help me resolve this issue? I have tried everything I have found.


The problem is with flat category, if I enable flat category then error occurs, and if I disable flat category it is working fine.

  • which magento version you used? any other category related extension are there? – chandresh chauhan Oct 16 '19 at 6:00
  • no other category extension. And I am using magento 2.2.8. Please see tags that I have attached – Shoaib Munir Oct 16 '19 at 6:07

can you try this code it's works for me

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

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

$categoryId = 4;
$sku = 'Jacket';


$categoryIds = [3]; // your category ids Array like [2,3,5]
$product = $objectManager->get('Magento\Catalog\Model\Product')->loadByAttribute('sku', $sku);
  • I have tried same thing, but getting error on this: $CategoryLinkRepository->deleteByIds($categoryId,$sku); please check question – Shoaib Munir Oct 16 '19 at 5:53
  • i have tested code in magento 2.2.8 but i'm not getting any errors. – chandresh chauhan Oct 16 '19 at 6:35
  • Have you tried this on frontend or backend? is that you custom script or you are doing it in controller? – Shoaib Munir Oct 16 '19 at 6:36
  • on frontend using custom root script for testing – chandresh chauhan Oct 16 '19 at 6:41
  • that's it mate :). In custom script you can define scope of file like adminhtml or cronjob etc. But in frontend controller it would cause issue, this is what I am facing :( – Shoaib Munir Oct 16 '19 at 6:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.