Skip to content

Commit

Permalink
[10.x] Fix runPaginationCountQuery not working properly for union que…
Browse files Browse the repository at this point in the history
…ries (#52314)

* Fix runPaginationCountQuery not working properly for union queries

* Added tests
  • Loading branch information
chinleung authored Jul 30, 2024
1 parent 82e9dbc commit 8937e25
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -3016,10 +3016,10 @@ protected function runPaginationCountQuery($columns = ['*'])
->get()->all();
}

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

return $this->cloneWithout($without)
->cloneWithoutBindings($this->unions ? ['order'] : ['select', 'order'])
->cloneWithoutBindings($this->unions ? ['unionOrder'] : ['select', 'order'])
->setAggregate('count', $this->withoutSelectAliases($columns))
->get()->all();
}
Expand Down
28 changes: 28 additions & 0 deletions tests/Database/DatabaseQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2070,6 +2070,34 @@ public function testGetCountForPaginationWithUnion()
$this->assertEquals(1, $count);
}

public function testGetCountForPaginationWithUnionOrders()
{
$builder = $this->getBuilder();
$builder->from('posts')->select('id')->union($this->getBuilder()->from('videos')->select('id'))->latest();

$builder->getConnection()->shouldReceive('select')->once()->with('select count(*) as aggregate from ((select "id" from "posts") union (select "id" from "videos")) as "temp_table"', [], true)->andReturn([['aggregate' => 1]]);
$builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function ($builder, $results) {
return $results;
});

$count = $builder->getCountForPagination();
$this->assertEquals(1, $count);
}

public function testGetCountForPaginationWithUnionLimitAndOffset()
{
$builder = $this->getBuilder();
$builder->from('posts')->select('id')->union($this->getBuilder()->from('videos')->select('id'))->take(15)->skip(1);

$builder->getConnection()->shouldReceive('select')->once()->with('select count(*) as aggregate from ((select "id" from "posts") union (select "id" from "videos")) as "temp_table"', [], true)->andReturn([['aggregate' => 1]]);
$builder->getProcessor()->shouldReceive('processSelect')->once()->andReturnUsing(function ($builder, $results) {
return $results;
});

$count = $builder->getCountForPagination();
$this->assertEquals(1, $count);
}

public function testWhereShortcut()
{
$builder = $this->getBuilder();
Expand Down

0 comments on commit 8937e25

Please sign in to comment.