1 Comment

getProductCount() function returning similar result for every category

How to preview an uploaded image via custom options?
How to preview an uploaded image via custom options?

Hello I am trying to get category name and category product count using category Id . In my results I am getting exact category name but product count is duplicating.

foreach ($category as $categoryId) {
    if (!is_null($categoryId)) {
        $categoryLoadData = Mage::getSingleton('catalog/category')->load($categoryId);
        $categoryArray[$count]['id'] = $categoryId;
        $categoryArray[$count]['name'] = $categoryLoadData->getName();
        $categoryArray[$count]['productCount'] = $categoryLoadData->getProductCount();
        Mage::log($categoryId.' - '.$categoryLoadData->getName().' - '.$categoryLoadData->getProductCount(),null,'final.log'
                                . '');
        $count++;
      }
 }
    Mage::log($categoryArray,null,'catrblock.log');

I got result in final.log

14 - category_name_1 - 74
7 - category_name_2 - 74

Result I got in catrblock.log

Array
(
 [0] => Array
 (
     [id] => 14
     [name] => category_name_1
     [productCount] => 74
 )

 [1] => Array
 (
     [id] => 7
     [name] => category_name_2
     [productCount] => 74
 )

)

Related Posts

How to preview an uploaded image via custom options?
How to preview an uploaded image via custom options?

1 Comment on this article

  • User November 12, 2016

    To me the problem here is that you’re using a singleton:

    Mage::getSingleton('catalog/category')->load($categoryId);
    

    Thus, even if you reload the singleton in a loop, there can be some persistent data in your object.

    You should use models instead:

    Mage::getModel('catalog/category')->load($categoryId);
    

    If you need clarification about when to use singletons, I reckon you should check this very good SE post:

    http://stackoverflow.com/questions/18756753/magento-getsingleton-vs-getmodel-issue

    Reply

Add a comment