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

[4.x] Order by primary key when using lazy() or chunk() #9956

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Query/EloquentQueryBuilder.php
Expand Up @@ -440,6 +440,8 @@ protected function invalidOperatorAndValue($operator, $value)
*/
public function chunk($count, callable $callback)
{
$this->enforceOrderBy();

$page = 1;

do {
Expand Down Expand Up @@ -483,6 +485,8 @@ public function lazy($chunkSize = 1000)
throw new InvalidArgumentException('The chunk size should be at least 1');
}

$this->enforceOrderBy();

return LazyCollection::make(function () use ($chunkSize) {
$page = 1;

Expand All @@ -499,4 +503,16 @@ public function lazy($chunkSize = 1000)
}
});
}

/**
* Add a generic "order by" clause if the query doesn't already have one.
*
* @return void
*/
protected function enforceOrderBy()
{
if (empty($this->builder->query->orders) && empty($this->builder->query->unionOrders)) {
$this->orderBy($this->builder->getModel()->getQualifiedKeyName(), 'asc');
}
}
}