diff --git a/CHANGELOG.md b/CHANGELOG.md index 291694453..37f2300f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Added +- Backport support for cursor pagination [#2358](https://github.com/jenssegers/laravel-mongodb/pull/2358) by [@Jeroenwv](https://github.com/Jeroenwv). + +## [3.9.0] - 2022-02-17 + ### Added - Compatibility with Laravel 9.x [#2344](https://github.com/jenssegers/laravel-mongodb/pull/2344) by [@divine](https://github.com/divine). diff --git a/src/Eloquent/Builder.php b/src/Eloquent/Builder.php index 398f3893b..bfa3d634a 100644 --- a/src/Eloquent/Builder.php +++ b/src/Eloquent/Builder.php @@ -217,4 +217,27 @@ public function getConnection() { return $this->query->getConnection(); } + + /** + * @inheritdoc + */ + protected function ensureOrderForCursorPagination($shouldReverse = false) + { + if (empty($this->query->orders)) { + $this->enforceOrderBy(); + } + + if ($shouldReverse) { + $this->query->orders = collect($this->query->orders)->map(function ($direction) { + return $direction === 1 ? -1 : 1; + })->toArray(); + } + + return collect($this->query->orders)->map(function ($direction, $column) { + return [ + 'column' => $column, + 'direction' => $direction === 1 ? 'asc' : 'desc', + ]; + })->values(); + } } diff --git a/tests/QueryTest.php b/tests/QueryTest.php index cc22df587..b2716e178 100644 --- a/tests/QueryTest.php +++ b/tests/QueryTest.php @@ -383,6 +383,29 @@ public function testPaginate(): void $this->assertEquals(1, $results->currentPage()); } + public function testCursorPaginate(): void + { + $results = User::cursorPaginate(2); + $this->assertEquals(2, $results->count()); + $this->assertNotNull($results->first()->title); + $this->assertNotNull($results->nextCursor()); + $this->assertTrue($results->onFirstPage()); + + $results = User::cursorPaginate(2, ['name', 'age']); + $this->assertEquals(2, $results->count()); + $this->assertNull($results->first()->title); + + $results = User::orderBy('age', 'desc')->cursorPaginate(2, ['name', 'age']); + $this->assertEquals(2, $results->count()); + $this->assertEquals(37, $results->first()->age); + $this->assertNull($results->first()->title); + + $results = User::whereNotNull('age')->orderBy('age', 'asc')->cursorPaginate(2, ['name', 'age']); + $this->assertEquals(2, $results->count()); + $this->assertEquals(13, $results->first()->age); + $this->assertNull($results->first()->title); + } + public function testUpdate(): void { $this->assertEquals(1, User::where(['name' => 'John Doe'])->update(['name' => 'Jim Morrison']));