Magento-获取集合中的类别和子类别
我的magento商店中有以下类别结构Magento-获取集合中的类别和子类别,magento,collections,foreach,Magento,Collections,Foreach,我的magento商店中有以下类别结构 - root - category 0 (ID 26) - category 1 (main) - category A (sub) - category V (sub) - category 2 (main) - category G (sub) - category J (sub) - cate
- root
- category 0 (ID 26)
- category 1 (main)
- category A (sub)
- category V (sub)
- category 2 (main)
- category G (sub)
- category J (sub)
- category E (sub)
- category 3 (main)
- category L (sub)
等等
在页面上,我希望能够输出以下内容:
1. get each (main) category and its name and url
2. get the first (sub) category in (main) and its icon (custom attribute)
因此,它将为每个:
<a href="main-cat-link"><img src="main-cat-first-sub-icon"></a>
<a href="main-cat-link">main-cat-name</a>
给出类似于:
<category 1 link><category A icon img></link>
<category 1 link><category 1 name>
<category 2 link><category G icon img>
<category 2 link><category 2 link>
<category 3 link><category L icon img>
<category 3 link><category 3 link>
这样做的最佳方式是什么?到目前为止,我已经:
<?php
$_id = 26 // category 0
$_main_categories = Mage::getModel('catalog/category')
->getCollection()
->addFieldToFilter('parent_id', array('eq'=>$_id))
->addAttributeToFilter('is_active', 1)
->addAttributeToSelect(array('id','name','url'))
foreach($_main_categories as $_main_cat)
{
// load full main category
$_category = Mage::getModel('catalog/category')->load($_main_cat->getId());
// get sub category's children
$_main_cat_subs = $_category->getChildrenCategories();
// loop through sub catagories, get icon in first and break
foreach($_main_cat_subs as $_sub_cat)
{
// load full sub category
$_sub = Mage::getModel('catalog/category')->load($_sub_cat->getId());
$i++;
$_icon = $_sub_cat->getIcon();
}
if( $i >= 1 ){
break; // as i only want the first one
}
}
// output
?>
<a href="<?php echo $_main_cat->getUrl() ?>">
<img src="<?php echo $_icon ?>">
</a>
<a href="<?php echo $_main_cat->getUrl() ?>">
<?php echo $_main_cat->getName() ?>
</a>
<?php
}
?>
这是可行的,但在foreach循环中加载完整类别模型两次似乎是非常糟糕的做法,而且当站点增长时可能需要很长时间
执行上述性能优化的最佳方法是什么?您可以优化的是:
$_category = Mage::getModel('catalog/category')->load($_main_cat->getId());
在这里,您将再次从数据库加载该类别。虽然您已经加载了一个集合,但是您应该使用正确的属性将所需的所有类别放入该集合中
然后,使用此集合函数获取类别实体,而不是上面的代码:
$_category = $_main_categories->getItemById($_main_cat->getId());
//...
$_sub = $_main_categories->getItemById($_sub_cat->getId());
您应该看到性能的明显改善,特别是如果您有很多类别