Let's say I have a model User, and it's got 1000 entries. I want to build an array of ids of all the users.
I write -
User::all(). Now this would try to fetch all the 1000 records in one go. Which I believe would eat up lot of memory. The second approach would be to use -
I want to understand whether the second approach would actually make 20 queries to the database to fetch all 1000 records in order to be light on memory. Or does it simply fetch all the records like User::all() and then divide the data into chunks of 50?
Yeah it will perform a query per chunk callback. So first it will perform a query using limit(50) and then it will return those values to the callback. After that it will perform a new query using offset(50) and limit(50). This way it will calculate all the right results for you and keep the memory low.
User::all() will run the query and store the result in a Collection. I didn't even know that a chunk-method existed there as well, but yes, that will run only ONE query and fetch all results, so any performance-improvement running on a large table will be lost.