1

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
 )

)
1

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:

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

  • Thanks a lot Digital Pianism it worked for me . Thank you for the description – PRashant PUrohit Mar 14 '16 at 11:09
  • @PRashantPUrohit no problem, see my edit for more details about the use of singletons. – Raphael at Digital Pianism Mar 14 '16 at 11:13
  • Digital Pianism thank you for the link it will help me a lot just a request can you up vote my question if you can :) – PRashant PUrohit Mar 14 '16 at 11:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.