2012-04-04 64 views
4

在我的產品網格頁面上,我希望爲每個產品展示它所在的「最深」類別。Magento爲每個產品找到最深的類別

這是我到目前爲止基於其他一些類似問題的主題。

$res = Mage::getSingleton('core/resource'); 
    $eav = Mage::getModel('eav/config'); 
    $nameattr = $eav->getAttribute('catalog_category', 'name'); 
    $nametable = $res->getTableName('catalog/category') . '_' . $nameattr->getBackendType(); 
    $nameattrid = $nameattr->getAttributeId(); 

    $collection 
    ->joinTable('catalog/category_product', 
    'product_id=entity_id', array('single_category_id' => 'category_id'), 
    null,'left') 

    ->joinTable('catalog_category_entity', 
    "entity_id=single_category_id", array('cat_level' => 'level','cat_path' => 'path'), 
    null,'left') 

    //->addAttributeToSort('entity_id', 'ASC') 
    //->addAttributeToSort('cat_level', 'ASC') 
    //->groupByAttribute('entity_id') 

    ->joinTable($nametable, 
    "entity_id=single_category_id", array('single_category_name' => 'value'), 
    "attribute_id=$nameattrid", 'left') 
    ->printLogQuery(true);exit; 

這使我得到以下結果:

Screenshot MYSQL results

所以我得到了我的產品收集並添加三列。顯然,對於entity_id 310'Fauteuils'是最深的類別。我現在唯一要做的就是通過entity_id根據最高的cat_level對結果進行「分組」。然而,'group by'不會給我想要的結果。

感謝

回答

4

這裏有一個簡單的解決方案,你可以採取的想法來自:

$category = $product->getCategory(); 
$path  = explode('/', $category->getPath()); 
$deepestId = $path[count($path) - 1]; 

$deepestCategory = Mage::getModel('catalog/category')->load($deepestId); 

Zend_Debug::dump($deepestCategory->getData());exit; 

你會想看看在分類表中的列path,然後找到最後一類ID在路徑中。

+0

謝謝,但我沒有問題得到路徑或類別級別,因爲你可以看到我目前的進度(和截圖)。另外,加載每個類別並不是非常聰明的性能。 – 2012-04-04 19:56:51

+0

它完全爲我工作。這是一個非常好的解決方案。 – RPDeshaies 2014-03-20 13:57:14

相關問題