I am trying to create and delete categories in Magento 2 but am facing some issues while doing it when Flat Categories
option is enabled.
The weird thing is, my code works fine when called from a bootstrap file like this.
< ?php
use MagentoFrameworkAppBootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('MagentoFrameworkAppState');
$state->setAreaCode(MagentoFrameworkAppArea::AREA_FRONTEND);
$registry = $obj->get('MagentoFrameworkRegistry');
$registry->register("isSecureArea", true);
$category = $obj->create('MagentoCatalogModelCategoryFactory')->create();
$data = ['name'=>'Test', 'url_key'=> 'test'];
$parentId = 52;
$parent = $categoryFactory->create()->load($parentId);
$category = $categoryFactory->create();
$category->setData($data);
$category->addData([
'parent_id' => $parentId,
'path' => $parent->getPath(),
'default_sort_by' => 'position',
'display_mode' => MagentoCatalogModelCategory::DM_PRODUCT,
'include_in_menu' => 0,
'is_anchor' => 1
]);
$category->setStoreId(0)->save();
die('
done');
But when I execute the same code form a custom API controller, it fails with the following error while calling $category->save()
when storeId is set to 0.
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'm23.catalog_category_flat' doesn't exist, query was: SELECT `catalog_category_flat`.* FROM `catalog_category_flat` WHERE (`catalog_category_flat`.`entity_id`='52')
If I set storeId to 1 then I get this error
Uncaught Error: Call to undefined method Magento\Catalog\Model\ResourceModel\Category\Flat::getEntityTable()
I solved a similar issue in Magento 1.9 by using this
$category = Mage::getModel('catalog/category', array('disable_flat' => true));
Any idea how to solve this in Magento 2? :/
Thanks