diff --git a/src/ORM/DataQuery.php b/src/ORM/DataQuery.php index 7599ffac7b4..e909b217fb6 100644 --- a/src/ORM/DataQuery.php +++ b/src/ORM/DataQuery.php @@ -395,7 +395,12 @@ protected function ensureSelectContainsOrderbyColumns($query, $originalSelect = // format internally; then this check can be part of selectField() $selects = $query->getSelect(); if (!isset($selects[$col]) && !in_array($qualCol, $selects)) { - $query->selectField($qualCol); + // Use the original select if possible. + if (array_key_exists($col, $originalSelect)) { + $query->selectField($originalSelect[$col], $col); + } else { + $query->selectField($qualCol); + } } } else { $qualCol = '"' . implode('"."', $parts) . '"'; diff --git a/tests/php/ORM/DataQueryTest.php b/tests/php/ORM/DataQueryTest.php index f79da3f8c6a..31c74867265 100644 --- a/tests/php/ORM/DataQueryTest.php +++ b/tests/php/ORM/DataQueryTest.php @@ -326,6 +326,21 @@ public function testSurrogateFieldSort() ); } + public function testCustomFieldWithAliasSort() + { + $query = new DataQuery(DataQueryTest\ObjectE::class); + $query->selectField(sprintf( + '(case when "Title" = %s then 1 else 0 end)', + DB::get_conn()->quoteString('Second') + ), 'CustomColumn'); + $query->sort('CustomColumn', 'DESC', true); + $query->sort('SortOrder', 'ASC', false); + $this->assertEquals( + ['Second', 'First', 'Last'], + $query->column('Title') + ); + } + public function testComparisonClauseDateStartsWith() { DB::query("INSERT INTO \"DataQueryTest_F\" (\"MyDate\") VALUES ('1988-03-04 06:30')");