diff --git a/model/queries/SQLSelect.php b/model/queries/SQLSelect.php index eecbba2bf..5ba1bcbd8 100644 --- a/model/queries/SQLSelect.php +++ b/model/queries/SQLSelect.php @@ -334,10 +334,12 @@ class SQLSelect extends SQLConditionalExpression { // Move the clause to the select fragment, substituting a placeholder column in the sort fragment. $clause = trim($clause); - $column = "_SortColumn{$i}"; + do { + $column = "_SortColumn{$i}"; + $i++; + } while(array_key_exists('"' . $column . '"', $this->orderby)); $this->selectField($clause, $column); $clause = '"' . $column . '"'; - $i++; } $orderby[$clause] = $dir; } diff --git a/tests/model/SQLQueryTest.php b/tests/model/SQLQueryTest.php index ec43668f8..5d0fbf742 100755 --- a/tests/model/SQLQueryTest.php +++ b/tests/model/SQLQueryTest.php @@ -125,6 +125,18 @@ class SQLQueryTest extends SapphireTest { $this->assertTrue($query->canSortBy('Name')); } + /** + * Test multiple order by SQL clauses. + */ + public function testAddOrderBy() { + $query = new SQLQuery(); + $query->setSelect('ID', "Title")->setFrom('Page')->addOrderBy('(ID % 2) = 0', 'ASC')->addOrderBy('ID > 50', 'ASC'); + $this->assertSQLEquals( + 'SELECT ID, Title, (ID % 2) = 0 AS "_SortColumn0", ID > 50 AS "_SortColumn1" FROM Page ORDER BY "_SortColumn0" ASC, "_SortColumn1" ASC', + $query->sql($parameters) + ); + } + public function testSelectWithChainedFilterParameters() { $query = new SQLQuery(); $query->setSelect(array("Name","Meta"))->setFrom("MyTable");