diff --git a/core/model/DataObject.php b/core/model/DataObject.php index 7f803e88e..09f816ae4 100755 --- a/core/model/DataObject.php +++ b/core/model/DataObject.php @@ -2650,10 +2650,13 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity $query->from[] = $join; // In order to group by unique columns we have to group by everything listed in the select foreach($query->select as $field) { + // Skip the _SortColumns; these are only going to be aggregate functions + if(preg_match('/AS\s+\"?_SortColumn/', $field, $matches)) { + // Identify columns with aliases, and ignore the alias. Making use of the alias in // group by was causing problems when those queries were subsequently passed into // SQLQuery::unlimitedRowCount. - if(preg_match('/^(.*)\s+AS\s+(\"[^"]+\")\s*$/', $field, $matches)) { + } else if(preg_match('/^(.*)\s+AS\s+(\"[^"]+\")\s*$/', $field, $matches)) { $query->groupby[] = $matches[1]; // Otherwise just use the field as is } else { diff --git a/tests/DataObjectTest.php b/tests/DataObjectTest.php index 022592990..650412865 100755 --- a/tests/DataObjectTest.php +++ b/tests/DataObjectTest.php @@ -738,6 +738,10 @@ class DataObjectTest extends SapphireTest { $player = $newTeam->Players()->First(); $this->assertEquals('Sam', $player->FirstName); $this->assertEquals("Prop", $player->Position); + + // Check that ordering a many-many relation by an aggregate column doesn't fail + $player = $this->objFromFixture('DataObjectTest_Player', 'player2'); + $player->Teams("", "count(DISTINCT \"DataObjectTest_Team_Players\".\"DataObjectTest_PlayerID\") DESC"); } /**