diff --git a/src/ORM/DataQuery.php b/src/ORM/DataQuery.php index 7599ffac7..e909b217f 100644 --- a/src/ORM/DataQuery.php +++ b/src/ORM/DataQuery.php @@ -395,7 +395,12 @@ class DataQuery // 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 f79da3f8c..31c748672 100644 --- a/tests/php/ORM/DataQueryTest.php +++ b/tests/php/ORM/DataQueryTest.php @@ -326,6 +326,21 @@ class DataQueryTest extends SapphireTest ); } + 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')");