Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Implement lazyById in descending order #39646

Merged
merged 6 commits into from
Nov 18, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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