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

Mac*_*Man 5 parent magento 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();
}
Run Code Online (Sandbox Code Playgroud)

在我知道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;
}
Run Code Online (Sandbox Code Playgroud)

然而,它实际上并不起作用.第一种方法可以很好地创建类别,但在运行第二种方法后,我甚至无法加载管理面板来显示类别.

我究竟做错了什么?

编辑:

我向第二种方法发送了错误的id.它似乎已正确填充数据库表catalog_category_entity,但现在管理视图中的类别无法正确显示.它们仍然显示为根类别是父类,在数据库中,新父类显示为具有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;
}
Run Code Online (Sandbox Code Playgroud)

小智 1

你可以只使用setParentId()

$category->setParentId($parentCategoryId);
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用类别 Api 模型来创建类别:

$categoryData = array(
    'name'        => $name,
    'url_key'     => $urlKey,
    'is_active'   => '1',
);

$categoryApi = Mage::getModel('catalog/category_api_v2');
$categoryId = $categoryApi->create($parentCategoryId, $categoryData, $store)
Run Code Online (Sandbox Code Playgroud)