1

I have a data-install script that I'd like to update each customer with a new custom id. I'm restricting the update to 2 customer groups, so I'm fetching the customers like so:

 $customers = Mage::getModel('customer/customer')->getCollection() ->addFieldToFilter('group_id', array('in' => array('5', '11'))); 

This returns over 6000 customers. I then loop over the customers, add two new attributes and save:

$myIncrementalValue = 0; foreach($customers as $customer) { $myIncrementalValue++; $customer->setData('myincrementalvalue', $myIncrementalValue) ->setData('special_code', 'OL-' . $customer->getId() . '-' . $myIncrementalValue) ->save(); } 

This is very taxing on my server and the script always fatals due to wait timeouts. Can anyone tell me a cheaper way of executing mass custom updates on customers.

1 Answer 1

1

This one was tricky. Lots of trial & error but I finally figured it out thanks to this article.

Basically, I used the resource iterator's walk() method, passing in the collection's select query and a callback like so:

Mage::getSingleton('core/resource_iterator')->walk($customers->getSelect(), array(function($args) { $increment = $args['idx'] + 1; $customer = Mage::getModel('customer/customer'); $customer->setData($args['row']); // map data to customer model $customer->setData('myincrementalvalue', $increment); $customer->setData('special_code', 'OL-' . $customer->getId() . '-' . $increment); $resource = $customer->getResource(); $resource->saveAttribute($customer, 'myincrementalvalue'); $resource->saveAttribute($customer, 'special_code'); 

}));

I was having trouble passing in an incremental argument to the callback by reference, but was fortunate enough to make use of the 'idx' argument passed in by walk(), since my incremental value started at 0.

This was successful and the script complete in about 20-30 seconds, updating each of the 6000+ customers!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.