Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento model collections - save data

Tags:

magento

So I'm loading a collection of products using this code:

$magento_time= 'some time string';
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(
    array('attribute'=> 'updated_at', 'gt'=> date('Y-m-d H:i:s', strtotime($magento_time))),
));    
$collection->save();

And getting this error in return on save:

Warning: Invalid argument supplied for foreach()  in /var/www/magento/app/code/core/Mage/Eav/Model/Entity/Abstract.php on line 970

#0 /var/www/magento/app/code/core/Mage/Eav/Model/Entity/Abstract.php(970): mageCoreErrorHandler(2, 'Invalid argumen...', '/var/www/magent...', 970, Array)
#1 /var/www/magento/app/code/core/Mage/Eav/Model/Entity/Abstract.php(925): Mage_Eav_Model_Entity_Abstract->_collectSaveData(Object(Mage_Catalog_Model_Product))
#2 /var/www/magento/app/code/core/Mage/Core/Model/Abstract.php(251): Mage_Eav_Model_Entity_Abstract->save(Object(Mage_Catalog_Model_Product))
#3 /var/www/magento/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php(845): Mage_Core_Model_Abstract->save()
#4 /var/www/magento/app/code/local/MyModule/controllers/IndexController.php(16): Mage_Eav_Model_Entity_Collection_Abstract->save()
#5 /var/www/magento/app/code/core/Mage/Core/Controller/Varien/Action.php(376): MyModule_IndexController->sayHelloAction()
#6 /var/www/magento/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(248): Mage_Core_Controller_Varien_Action->dispatch('sayHello')
#7 /var/www/magento/app/code/core/Mage/Core/Controller/Varien/Front.php(158): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#8 /var/www/magento/app/Mage.php(459): Mage_Core_Controller_Varien_Front->dispatch()
#9 /var/www/magento/index.php(68): Mage::run()
#10 {main}

How do I save products back to the database after they've been loaded into a collection?

like image 749
leepowers Avatar asked Nov 19 '09 04:11

leepowers


2 Answers

Changing the following worked for me:

Manually set the current store:

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

Save each collection independently.

foreach ($collection as $entry) {
  $entry->save();
}

EDIT:

Note the Magento API has changed significantly since I first asked this question ~2.5 years ago - this answer may no longer apply.

like image 112
leepowers Avatar answered Oct 21 '22 09:10

leepowers


You do a foreach and save elements one by one.

like image 27
Elzo Valugi Avatar answered Oct 21 '22 09:10

Elzo Valugi