Skip to content

Commit 16ad066

Browse files
authored
[12.x] Fix: Make Paginated Queries Consistent Across Pages (#55176)
* Add failing tests * Make paginated queries more consistent across pages
1 parent a9d8775 commit 16ad066

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/Illuminate/Database/Query/Builder.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2790,7 +2790,9 @@ public function forPageBeforeId($perPage = 15, $lastId = 0, $column = 'id')
27902790
{
27912791
$this->orders = $this->removeExistingOrdersFor($column);
27922792

2793-
if (! is_null($lastId)) {
2793+
if (is_null($lastId)) {
2794+
$this->whereNotNull($column);
2795+
} else {
27942796
$this->where($column, '<', $lastId);
27952797
}
27962798

@@ -2810,7 +2812,9 @@ public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id')
28102812
{
28112813
$this->orders = $this->removeExistingOrdersFor($column);
28122814

2813-
if (! is_null($lastId)) {
2815+
if (is_null($lastId)) {
2816+
$this->whereNotNull($column);
2817+
} else {
28142818
$this->where($column, '>', $lastId);
28152819
}
28162820

tests/Database/DatabaseQueryBuilderTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2360,6 +2360,28 @@ public function testForPage()
23602360
$this->assertSame('select * from "users" limit 0 offset 0', $builder->toSql());
23612361
}
23622362

2363+
public function testForPageBeforeId()
2364+
{
2365+
$builder = $this->getBuilder();
2366+
$builder->select('*')->from('users')->forPageBeforeId(15, null);
2367+
$this->assertSame('select * from "users" where "id" is not null order by "id" desc limit 15', $builder->toSql());
2368+
2369+
$builder = $this->getBuilder();
2370+
$builder->select('*')->from('users')->forPageBeforeId(15, 0);
2371+
$this->assertSame('select * from "users" where "id" < ? order by "id" desc limit 15', $builder->toSql());
2372+
}
2373+
2374+
public function testForPageAfterId()
2375+
{
2376+
$builder = $this->getBuilder();
2377+
$builder->select('*')->from('users')->forPageAfterId(15, null);
2378+
$this->assertSame('select * from "users" where "id" is not null order by "id" asc limit 15', $builder->toSql());
2379+
2380+
$builder = $this->getBuilder();
2381+
$builder->select('*')->from('users')->forPageAfterId(15, 0);
2382+
$this->assertSame('select * from "users" where "id" > ? order by "id" asc limit 15', $builder->toSql());
2383+
}
2384+
23632385
public function testGetCountForPaginationWithBindings()
23642386
{
23652387
$builder = $this->getBuilder();

0 commit comments

Comments
 (0)