I’m using CakePHP with $modelName->find(…) calls to select quite a number of rows (could be hundreds)
Normally, in PHP/MySQL of course this wouldn’t be a problem, as you fetch them in a while loop. But, CakePHP loads all rows in to an array which exhausts the memory limit.
Is there a way to use the $modelName->find(…) constructs but return an iterator to fetch each row on demand?
Thanks, David
No, out of the box Cake PHP (and ActiveRecord in general) doesn’t support iterating over a result set like that. If you have a use case where you actually need all the records of a table, you’re probably better off using raw SQL. (or rethinking your use case).
You could also (and have likely already thought to) use an offset of some kind, and call ->find multiple times. If you take this approach don’t forget to order your result set by some field to ensure a deterministic result. Databases only seem to return sorted rows when you leave an ORDER BY off. I haven’t personally tried this, and it seems inefficient from a multiple queries standpoint, but it’s something worth trying.