Magento - 如何以编程方式为类别设置新的父级?

标签 magento parent categories

我正在使用此方法,因此创建新类别:

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/

相关文章:

metadata - Tridion 2009 - 检索组件的父文件夹 TCM

objective-c - Objective C 关于类别的解释?

php - 你如何创建像 pinterest 这样的搜索栏?

MAGENTO 从子类别中获取描述

html - Magento 基本字体大小

php - Magento 不显示完整的产品名称

ios - 分页引擎架构 - iOS

mysql - BLOB/TEXT 列 'value' 用于没有 key 长度的 key 规范

jquery parent /最近的不工作

.net - MDIParent 平铺 child