Alex Rivera | Logout

Multiple calls to $model->save() in Magento over-writing data

Asked 2012-05-29T10:58:40.140
9

I am developing a custom Magento module that needs to save a list of email addresses into a custom table. The relevant code looks like this:

foreach($this->getNewSubscriptionsForAPI() as $email){
            $requestModel->setEmail($email);
            $requestModel->setAction('subscribe');
            $requestModel->setPosted(date('Y-m-d H:i:s'));
            $requestModel->save();
        }

The getNewSubscriptionsForAPI() method is returning valid data, and the $requestModel is a valid Magento model.

When this loop runs, however, the database adaptor simple overwrites each record on top of the previous one. Ie, if I repeatedly hit 'browse' in phpMyAdmin I can see different email addresses being written to the database but always in the same row, overwriting the previous entry. The id field is correctly set up: as primary key, set to AUTO_INCREMENT, and flagged as the id field in the resource model.

What's interesting is that I can use the loop above to write successive records in the core newsletter/subscriber table with no problem.

I could, of course, simply unset() the model and get it back out of the Mage::getModel() at each cycle of the loop, but this (a) seems hugely wasteful, and (b) spoils my Dependency Injection setup for testing (where I don't want the code to be instantiating its own models, but using the ones I pass to it).

Can anyone point me in the right direction?

Edit
Report

1 Answer

9

Ah, it seems like I may have answered my own question. By including a call to $requestModel->unsetData(); just after the call to $requestModel->save() the loop works as intended.

unsetData is a method made available by Varien_Object, which Mage_Core_Model_Abstract inherits from.

I'm happy for someone to contribute a more elegant solution I'm happy to hear it.

answered 2012-05-29T11:05:22.710

Your Answer