Skip to content

Commit

Permalink
[8.x] Implement lazyById in descending order (#39646)
Browse files Browse the repository at this point in the history
* Implement lazyById in descending order

* fix need to use the parameter in the closure

* change the code a little so that it wont change the existing method signature so that it is a non-breaking change

* remove extra line

* Update BuildsQueries.php

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
moshe-autoleadstar and taylorotwell authored Nov 18, 2021
1 parent 7b782c9 commit bee1299
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions src/Illuminate/Database/Concerns/BuildsQueries.php
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,37 @@ public function lazy($chunkSize = 1000)
* @throws \InvalidArgumentException
*/
public function lazyById($chunkSize = 1000, $column = null, $alias = null)
{
return $this->orderedLazyById($chunkSize, $column, $alias);
}

/**
* Query lazily, by chunking the results of a query by comparing IDs in descending order.
*
* @param int $count
* @param string|null $column
* @param string|null $alias
* @return \Illuminate\Support\LazyCollection
*
* @throws \InvalidArgumentException
*/
public function lazyByIdDesc($chunkSize = 1000, $column = null, $alias = null)
{
return $this->orderedLazyById($chunkSize, $column, $alias, true);
}

/**
* Query lazily, by chunking the results of a query by comparing IDs in a given order.
*
* @param int $count
* @param string|null $column
* @param string|null $alias
* @param bool $descending
* @return \Illuminate\Support\LazyCollection
*
* @throws \InvalidArgumentException
*/
protected function orderedLazyById($chunkSize = 1000, $column = null, $alias = null, $descending = false)
{
if ($chunkSize < 1) {
throw new InvalidArgumentException('The chunk size should be at least 1');
Expand All @@ -227,13 +258,17 @@ public function lazyById($chunkSize = 1000, $column = null, $alias = null)

$alias = $alias ?? $column;

return LazyCollection::make(function () use ($chunkSize, $column, $alias) {
return LazyCollection::make(function () use ($chunkSize, $column, $alias, $descending) {
$lastId = null;

while (true) {
$clone = clone $this;

$results = $clone->forPageAfterId($chunkSize, $lastId, $column)->get();
if ($descending) {
$results = $clone->forPageBeforeId($chunkSize, $lastId, $column)->get();
} else {
$results = $clone->forPageAfterId($chunkSize, $lastId, $column)->get();
}

foreach ($results as $result) {
yield $result;
Expand Down

0 comments on commit bee1299

Please sign in to comment.