2015-02-24 39 views
2

我用這個$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

回答

4

基本上,當我們使用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

0

而不是打電話getModel()嘗試撥打getSingleton()

1

如果你想在第二個選項圖像的URL,你必須加載類:

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