我正在使用此方法,因此创建新类别:
private function createCat($name){
$category = Mage::getModel( 'catalog/category' );
$category->setStoreId( 0 );
$category->setName( $name ); // The name of the category
$category->setUrlKey( strtolower($name) ); // The category's URL identifier
$category->setIsActive( 1 ); // Is it enabled?
$category->setIsAnchor( 0 );
// Display mode can be 'PRODUCTS_AND_PAGE', 'PAGE', or 'PRODUCTS'
$category->setDisplayMode( 'PRODUCTS' );
$category->setPath( '1/3' ); // Important you get this right.
$category->setPageTitle( $name );
$category->save();
return $category->getId();
}
在知道 Magento 分配给类别的 ID 后,我在循环中调用以下方法为每个类别分配一个父类别:
private function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
$category->setPath( '1/3/'.$parent.'/'.$id ); // Important you get this right.
$category->save();
return;
}
但是它实际上不起作用。第一种方法可以很好地创建类别,但运行第二种方法后,我什至无法加载管理面板来显示类别。
我做错了什么?
编辑:
我向第二种方法发送了错误的 ID。它似乎已正确填充数据库表catalog_category_entity,但现在类别在管理 View 中无法正确显示。它们仍然显示为好像根类别是父级,并且在数据库中,新父级显示为具有 0 个子级。是否需要进行某种索引?
编辑:解决方案:
同时我已经找到了解决方案。要更改父类别,我需要使用内置类别 move() 方法移动其下的类别:
private function assignCat($id, $parent){
$category = Mage::getModel( 'catalog/category' )->load($id);
Mage::unregister('category');
Mage::unregister('current_category');
Mage::register('category', $category);
Mage::register('current_category', $category);
$category->move($parent);
return;
}
最佳答案
您可以只使用setParentId()
:
$category->setParentId($parentCategoryId);
或者,您可以使用类别 Api 模型来创建类别:
$categoryData = array(
'name' => $name,
'url_key' => $urlKey,
'is_active' => '1',
);
$categoryApi = Mage::getModel('catalog/category_api_v2');
$categoryId = $categoryApi->create($parentCategoryId, $categoryData, $store)
关于Magento - 如何以编程方式为类别设置新的父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047272/