Last active
December 20, 2019 06:55
-
-
Save vuthaihoc/b7137acb14f1a4ac1e414c6925c25a1c to your computer and use it in GitHub Desktop.
Call chunkById in reversed order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
Builder::macro( 'chunkByReveredId', function ( $count, callable $callback, $column = null, $alias = null ) { | |
$column = $column ?? $this->defaultKeyName(); | |
$alias = $alias ?? $column; | |
$lastId = $this->max('id') + 1; | |
do { | |
/** @var Builder $clone */ | |
$clone = clone $this; | |
// We'll execute the query for the given page and get the results. If there are | |
// no results we can just break and return from here. When there are results | |
// we will call the callback with the current chunk of these results here. | |
$results = $clone->forPageBeforeId( $count, $lastId, $column )->get(); | |
$countResults = $results->count(); | |
if ( $countResults == 0 ) { | |
break; | |
} | |
// 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 ( $callback( $results ) === false ) { | |
return false; | |
} | |
$lastId = $results->last()->{$alias}; | |
unset( $results ); | |
} while ( $countResults == $count ); | |
return true; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment