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){
$this->categoryLinkRepository->deleteByIds($previousCategoryId,$product->getSku());
}
//Assigning new categories
$this->categoryLinkManagement->assignProductToCategories($product->getSku(),$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:
https://github.com/magento/magento2/issues/9725#issuecomment-346621159
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:
$product->setCategoryIds($categories);
But above code appending categories, not replacing previous categories.
Can you help me resolve this issue? I have tried everything I have found.
Edit:
The problem is with flat category, if I enable flat category then error occurs, and if I disable flat category it is working fine.