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)
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();
| improve this answer | |
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();  
    } 
}
| improve this answer | |
  • 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 Mar 7 '19 at 3:19
  • 1
    You should also vaiud load/delete/save methods inside loops. – sv3n Mar 7 '19 at 17:00

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.