Thursday 3 November 2016

Best way to loop/iterate the catalog collection in Magento2

When i was doing mass status change in magento
I was facing with memory allocation in my localshot xammp
Total products i have around 7lakh in the admin grid. i tried to change the status about to 100 products,

i got this error

Fatal error: Allowed memory size of 805306368 bytes exhausted (tried to allocate 24 bytes) in C:\xampp\htdocs\mage-ee206\vendor\magento\zendframework1\library\Zend\Db\Statement\Pdo.php on line 291

==============
After spending one day time i got the solution

In one of my third party i found a iteration of products using foreach.. when i changed foreach to while it worked fine for me
i have tested for 30,50,100,500,700 products to changes the status and it was fine for me

I hope this may help you
original code
  $Prods = $this->_productFactory->create()->getCollection()->addIdFilter(<prodids>);
            $Prods->addAttributeToSelect(['status','<status>']);          
         
            foreach ($Prods as $prod) {
           
            $prodid = $prod->getId();
            $prod_status = $prod->getData('status');
=======================
Changed to 

$Prods = $this->_productFactory->create()->getCollection()->addIdFilter(<prodids>);
            $Prods->addAttributeToSelect(['status','<status>']);
            
            while ($prod = $Prods->fetchItem()) {            
            $prodid = $prod->getId();
            $prod_status = $prod->getStatus();
============

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home