如何对在管理员中显示的类别进行排序?


15

这是代码:

$category = Mage::getModel('catalog/category')->load(3);
$subCats = Mage::getModel('catalog/category')->load($category->getId())->getChildren();
$subCatIds = explode(',',$subCats);
$currentUrl = Mage::helper('core/url')->getCurrentUrl();

请指教,谢谢!

Answers:


24
$category = Mage::getModel('catalog/category')->load(3);
$children = Mage::getModel('catalog/category')->getCollection()->setStoreId(Mage::app()->getStore()->getId());
$children->addAttributeToSelect('*')
        ->addAttributeToFilter('parent_id', $category->getId())
        ->addAttributeToFilter('is_active', 1)//get only active categories if you want
        ->addAttributeToSort('position');//sort by position

foreach ($children as $child){
    //do something with $child
}

谢谢您的摘要,但是我想坚持我的代码,因为它已经在模板中应用了。如何将这种sort属性添加到中$subCats = Mage::getModel('catalog/category')->load($category->getId())->getChildren();?谢谢!
阿米尔·西迪克

3
您可以替换为getChildren()getChildrenCategories()并且应该对它们进行排序。但是,您仍然获得类别对象而不是ID。如果您需要ID,则可以遍历子类别并连接其ID。我不太了解您要达到的目标。
马里斯(Marius)

^^我希望它在getChildren()返回未排序ID并getChildrenCategories()返回已排序对象的地方有更清晰的记录。这为我清除了所有内容,到目前为止,magento文档本身还不清楚。
waffl 2014年

非常确定getChildrenCategories不适用于Flat Categories
Samyer

7

您可以尝试更改代码,以将getChilderCategories()和toArray函数很好地结合使用。

$category = Mage::getModel('catalog/category')->load(3);
$subCats = $category->getChildrenCategories();
$subCatIds = $subCats->toArray(array('entity_id'));

getChildrenCategories函数将以与admin部分相同的顺序为您提供一个集合,然后通过调用toArray并仅要求entit_id属性,您将具有一个类别ID数组

array(3) {
    [10]=> array(1) {
         ["entity_id"]=> string(2) "10"
    }
    [13]=> array(1) {
        ["entity_id"]=> string(2) "13"
    }
    [18]=> array(1) {
        ["entity_id"]=> string(2) "18"
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.