Blog: Don't Do This At Home #1: Update Many Rows By Looping on save()
Can you spot the problem in the following snippet?
The problem is that this program hydrates a lot of Book
objects for nothing, just to update them afterwards. It's a waste of time and memory. The good way to do this is to use the BookQuery::update()
method, as follows:
This second version takes almost no memory, and most important: the execution time doesn't depend on the number of records concerned by the change.
Note that you may need to use the first version, for instance if the model uses a behavior, and if this behavior has preSave()
or postSave()
hooks. In that case, instead of falling back to the first example, use the third argument of the update()
method. This will let your code reviewer know that you did that on purpose: