Skip to content

Commit 2eeb4f1

Browse files
authored
support cursor pagination with union query (#40848)
1 parent 2246744 commit 2eeb4f1

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/Illuminate/Database/Eloquent/Builder.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -865,9 +865,7 @@ public function cursorPaginate($perPage = null, $columns = ['*'], $cursorName =
865865
*/
866866
protected function ensureOrderForCursorPagination($shouldReverse = false)
867867
{
868-
$orders = collect($this->query->orders);
869-
870-
if ($orders->count() === 0) {
868+
if (empty($this->query->orders) && empty($this->query->unionOrders)) {
871869
$this->enforceOrderBy();
872870
}
873871

@@ -879,6 +877,10 @@ protected function ensureOrderForCursorPagination($shouldReverse = false)
879877
})->toArray();
880878
}
881879

880+
if ($this->query->unionOrders) {
881+
return collect($this->query->unionOrders);
882+
}
883+
882884
return collect($this->query->orders);
883885
}
884886

tests/Integration/Database/EloquentCursorPaginateTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,23 @@ public function testCursorPaginationOnTopOfColumns()
3636
$this->assertCount(15, TestPost::cursorPaginate(15, ['id', 'title']));
3737
}
3838

39+
public function testPaginationWithUnion()
40+
{
41+
TestPost::create(['title' => 'Hello world', 'user_id' => 1]);
42+
TestPost::create(['title' => 'Goodbye world', 'user_id' => 2]);
43+
TestPost::create(['title' => 'Howdy', 'user_id' => 3]);
44+
TestPost::create(['title' => '4th', 'user_id' => 4]);
45+
46+
$table1 = TestPost::query()->whereIn('user_id', [1, 2]);
47+
$table2 = TestPost::query()->whereIn('user_id', [3, 4]);
48+
49+
$result = $table1->unionAll($table2)
50+
->orderBy('user_id', 'desc')
51+
->cursorPaginate(1);
52+
53+
self::assertSame(['user_id'], $result->getOptions()['parameters']);
54+
}
55+
3956
public function testPaginationWithDistinct()
4057
{
4158
for ($i = 1; $i <= 3; $i++) {

0 commit comments

Comments
 (0)