Chunk block result set processing in Laravel, laravelchunk
If you need to process thousands of Eloquent results, you can usechunk
Command.chunk
The method will get a "block" Eloquent model and fill it with a given closure for processing. Usechunk
This method can effectively reduce memory consumption when processing a large number of datasets:
Flight::chunk(200, function ($flights) { foreach ($flights as $flight) { // }});
$all_ark=Arkvolume::chunk(50000, function ($flights) { foreach ($flights as $flight) { $GLOBALS['something'][] = $flight['id']; } }); var_dump($GLOBALS['something'] );exit;
This code executes an update of 100 pieces of data. After the execution is complete, it continues with another one hundred pieces of data ......
That is to say, each operation is a data block rather than the entire database.
Note that when a chunk with filtering conditions is used, if it is a self-Update, you will miss some data and then read the code:
User::where('approved', 0)->chunk(100, function ($users) { foreach ($users as $user) { $user->update(['approved' => 1]); }});
If you want to run the above Code, no error is reported,where
Filtering Conditionapproved
Is0
Ofuser
Thenapproved
With the new1
.
In this process, after the data in the first database is modified, the data in the next data block is selected from the modified data. At this time, the data changes, page also adds 1. Therefore, after the execution, only half of the data is updated.
If you do not understand it, let's take a look at the underlying implementation of chunk. The preceding code is used as an example. If there are a total of 400 pieces of data, the data is processed in 100 parts.
Page = 1: At the beginning, page is 1, and 1-pieces of data are selected for processing;
Page = 2: The first one hundred data recordsapproved
If all the values are 1, the data starts from 101st records during the next filtering, and the page is 2 at this time, the processed data will be the data before -.
And later.
public function chunk($count, callable $callback){ $results = $this->forPage($page = 1, $count)->get(); while (count($results) > 0) { // On each chunk result set, we will pass them to the callback and then let the // developer take care of everything within the callback, which allows us to // keep the memory low for spinning through large result sets for working. if (call_user_func($callback, $results) === false) { return false; } $page++; $results = $this->forPage($page, $count)->get(); } return true;}