diff --git a/lib/Relation.php b/lib/Relation.php index 90f35dae..81290fd4 100644 --- a/lib/Relation.php +++ b/lib/Relation.php @@ -816,10 +816,10 @@ private function firstOrLast(int $limit = null, bool $isAscending): array $pk = $this->table()->pk; if (!empty($pk)) { if (array_key_exists('order', $options)) { - $reverseCommand = $isAscending ? 'DESC' : 'ASC'; - - if (str_contains($options['order'], implode(" {$reverseCommand}, ", $this->table()->pk) . " {$reverseCommand}")) { - $options['order'] = SQLBuilder::reverse_order((string) $options['order']); + if (!$isAscending) { + if (str_contains($options['order'], implode(' DESC, ', $this->table()->pk) . ' DESC')) { + $options['order'] = SQLBuilder::reverse_order((string) $options['order']); + } } } elseif (!array_key_exists('having', $options)) { $command = $isAscending ? 'ASC' : 'DESC'; diff --git a/test/ActiveRecordFirstLastTest.php b/test/ActiveRecordFirstLastTest.php index fce6f899..5a43e94b 100644 --- a/test/ActiveRecordFirstLastTest.php +++ b/test/ActiveRecordFirstLastTest.php @@ -108,7 +108,8 @@ public function testLastWithCountOverridesLimit() public function testDoesNotClobberOrderOrLimit() { $rel = Author::limit(2)->order('author_id DESC'); - $this->assertEquals(1, $rel->first()->author_id); + $this->assertEquals(Author::last(), $rel->first()); + $this->assertEquals(Author::first(), $rel->last()); $authors = $rel->to_a(); $this->assertEquals(2, count($authors));