Skip to content

Commit

Permalink
[7.x] Run pagination count as subquery for group by and havings (#32624)
Browse files Browse the repository at this point in the history
Run pagination count as subquery for group by and havings
  • Loading branch information
taylorotwell authored May 1, 2020
1 parent dda3174 commit 4469c37
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 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,15 @@ public function getCountForPagination($columns = ['*'])
*/
protected function runPaginationCountQuery($columns = ['*'])
{
if ($this->groups || $this->havings) {
$clone = $this->cloneForPaginationCount();

return [(object) ['aggregate' => $this->newQuery()
->from(new Expression('('.$clone->toSql().') as '.$this->grammar->wrap('aggregate_table')))
->mergeBindings($clone)
->count(['*']), ]];
}

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

return $this->cloneWithout($without)
Expand All @@ -2265,6 +2272,17 @@ protected function runPaginationCountQuery($columns = ['*'])
->get()->all();
}

/**
* Clone the existing query instance for usage in a pagination subquery.
*
* @return self
*/
protected function cloneForPaginationCount()
{
return $this->cloneWithout(['orders', 'limit', 'offset'])
->cloneWithoutBindings(['order']);
}

/**
* Remove the column aliases since they will break count queries.
*
Expand Down

0 comments on commit 4469c37

Please sign in to comment.