2

I am processing some records and I need to set a datetime field to the current time for multiple rows. I have all the row IDs. What's the best way to do this with Magento 1? The SQL would be like this:

update
    my_table
set
    processed_on = "2015-09-09 11:11:04"
where
    id in(34, 56, 77, 39)

3 Answers 3

1

Instead of load/save inside foreach, you can try this:

$collection = Mage::getModel('your/model')->getCollection()
    ->addIdFilter(array(1,2,3));

foreach ($collection as $item) {
    $item->setProcessedOn('2015-09-09 11:11:04');
}
$collection->save();
0

To update existing rows in a model, you need to load each row first, call addData() with the new data, then save the row.

An example would look like this:

$rowIds = array(1,2,3)
foreach($rowIds as $rowId) {
    $data = array('processed_on' => "2015-09-09 11:11:04");

    $model = Mage::getModel('your_model')->load($rowId)->addData($data);   
    try {
        $model->setId($rowId)->save();  
        echo "Record updated";  
    } catch (Exception $e){  
        echo $e->getMessage();  
    } 
}
2
  • You should remove setId($id) before calling save() since $id is not defined and the model has already an id, because it is an existent record.
    – HelgeB
    Commented Mar 7, 2019 at 3:19
  • 1
    You should also vaiud load/delete/save methods inside loops.
    – sv3n
    Commented Mar 7, 2019 at 17:00
0

I know this answer is a bit late, but I ran into this requirement today and found another answer that let me avoid doing loops with loads or saves. For your code it could look something like this:

/** @var Mage_Core_Model_Resource $resource */
$resource = Mage::getSingleton('core/resource');
/** @var Magento_Db_Adapter_Pdo_Mysql $connection */
$connection = $resource->getConnection(Mage_Core_Model_Resource::DEFAULT_WRITE_RESOURCE);
$ids = array(34, 56, 77, 39);
$connection->update('my_table', ['processed_on' => "2015-09-09 11:11:04"], ['id IN(?)' => $ids]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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