获取分类图像

问题描述:

我用这个$categories在页面中获取分类图像

$categories = Mage::getModel('catalog/category') 
    ->getCollection() 
    ->addAttributeToSelect('*') 
    ->addAttributeToFilter('level',2) 
    ->addIsActiveFilter() 
    ->addAttributeToSort('position'); 

foreach($categories as $cat) {$children=$cat->getChildrenCategories();} 

选项1

//option 1 

$children = $category->getChildren(); 
foreach(explode(',', $children) as $child): 
$sub = Mage::getModel('catalog/category')->load($child); 

$sub->getName() // this return ok, name show up 
$sub->getImageUrl() // this return ok, image show up 

选项2级的作品,但无法获取图像的URL一些原因。

//option 2 
$children = $category->getChildrenCategories(); 
foreach($children as $sub): 

$sub->getName() // this return ok, name show up 
$sub->getImageUrl() // this return empty, image NOT show up so is other attribute beside name. 

有人可以解释区别吗?我怎么会去选择2

基本上,当我们使用getChildrenCategories()功能只有少数领域已经从类别字段集合检索 - >url_key,name,all_children,is_anchor

你可以看到,在Mage_Catalog_Model_Resource_Category类。所以如果想从功能tget图像的URL,然后只需添加addAttributeToFilter('image')

$collection = $category->getCollection(); 
$collection->addAttributeToSelect('url_key') 
    ->addAttributeToSelect('name') 
    ->addAttributeToSelect('all_children') 
    ->addAttributeToSelect('is_anchor') 
    ->setOrder('position', Varien_Db_Select::SQL_ASC) 
    ->joinUrlRewrite() 
->addAttributeToFilter('is_active', 1) 
    ->addIdFilter($category->getChildren()) 
->addAttributeToSelect('image'); 


foreach($category as $eachChildCat){ 

if ($image = $eachChildCat->getImage()) { 
    $url = Mage::getBaseUrl('media').'catalog/category/'.$image; 
    } 
} 

$ eachChildCat->的getImage()无法正常工作,然后使用$ eachChildCat->的getResource() - > getImage()

+0

它只有在清除加载的集合,添加属性以再次选择并加载集合时才有效:$ category-> getChildrenCategories() - > clear() - > addAttributeToSelect('image_url') - >加载();无论如何,这是比我的更好的方法;] – SeStro 2015-02-25 13:37:01

+0

非常感谢你,我真的很沮丧,如果我添加另一个 - >加载它增加我的加载时间整整2秒(没有缓存)。 – aahhaa 2015-02-25 14:46:20

+1

等。 igive你解决方案 – 2015-02-25 14:47:24

而不是打电话getModel()尝试拨打getSingleton()

如果你想在第二个选项图像的URL,你必须加载类:

$subcategory = Mage::getModel('catalog/category')->load($sub->getId()); 
$imageUrl = $subcategory->getImageUrl();