Magento - 获取集合中的类别和子类别

时间:2015-06-12 13:50:04

标签: 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)
            - 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循环中加载完整的类别模型两次,并且当网站增长可能需要很长时间。

明智地完成上述表现的最佳方式是什么?

1 个答案:

答案 0 :(得分:0)

您可以优化的是:

org.tmatesoft.svn.core.SVNAuthenticationException: svn: E170001: 
Commit failed (details follow):
svn: E170001: Authentication required for 'svn-user@svn+ssh://svn-server.ch'

在这里,您将从数据库中再次加载类别。虽然您已经加载了一个集合,但您应该将该集合中所需的所有类别与正确的属性放在一起。

然后使用这个少数收集函数代替上面的代码来获取类别实体:

$_category = Mage::getModel('catalog/category')->load($_main_cat->getId());

你应该看到性能的明显改善,特别是如果你有很多类别。