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

[7.x] Run pagination count as subquery for group by and havings #32624

Merged
merged 4 commits into from
May 1, 2020
Merged
Changes from 2 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
11 changes: 8 additions & 3 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2238,9 +2238,7 @@ public function getCountForPagination($columns = ['*'])
// Once we have run the pagination count query, we will get the resulting count and
// take into account what type of query it was. When there is a group by we will
// just return the count of the entire results set since that will be correct.
if (isset($this->groups)) {
return count($results);
} elseif (! isset($results[0])) {
if (! isset($results[0])) {
return 0;
} elseif (is_object($results[0])) {
return (int) $results[0]->aggregate;
Expand All @@ -2257,6 +2255,13 @@ public function getCountForPagination($columns = ['*'])
*/
protected function runPaginationCountQuery($columns = ['*'])
{
if ($this->groups || $this->havings) {
return [(object) ['aggregate' => $this->newQuery()
->from(new Expression('('.$this->toSql().') as '.$this->grammar->wrap('aggregate_table')))
->mergeBindings($this)
Copy link
Contributor

@staudenmeir staudenmeir May 1, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
->from(new Expression('('.$this->toSql().') as '.$this->grammar->wrap('aggregate_table')))
->mergeBindings($this)
->from($this, 'aggregate_table')

->count(['*']), ]];

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be faster to count the ID if there's one? instead of counting all columns?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't always know which columns are actually available. There is also a difference between count(*) and count(id): https://stackoverflow.com/a/3003533/4848587

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the $columns param is being passed by not used, maybe it should be
->count($columns), ]];

}

$without = $this->unions ? ['orders', 'limit', 'offset'] : ['columns', 'orders', 'limit', 'offset'];

return $this->cloneWithout($without)
Expand Down