diff --git a/model/DataList.php b/model/DataList.php index 4a0d65250..a5d2452f3 100644 --- a/model/DataList.php +++ b/model/DataList.php @@ -182,7 +182,7 @@ class DataList extends ViewableData implements SS_List { if(is_array($argumentArray)){ $sort = array(); foreach($argumentArray as $column => $direction) { - $sort []= '"'.$column.'" '.$direction; + $sort[]= ''.$this->getRelationName($column).' '.$direction; } $this->dataQuery->sort(implode(',', $sort)); return $this; @@ -241,6 +241,23 @@ class DataList extends ViewableData implements SS_List { return $this; } + /** + * Translates a Object relation name to a Database name and apply the relation join to + * the query + * + * @param string $field + * @return string + */ + public function getRelationName($field) { + if(strpos($field,'.') === false) { + return '"'.$field.'"'; + } + $relations = explode('.', $field); + $fieldName = array_pop($relations); + $relationModelName = $this->dataQuery->applyRelation($field); + return '"'.$relationModelName.'"."'.$fieldName.'"'; + } + /** * Translates the comparisator to the sql query * diff --git a/tests/model/DataListTest.php b/tests/model/DataListTest.php index 6bc70ed58..c6d7f8910 100755 --- a/tests/model/DataListTest.php +++ b/tests/model/DataListTest.php @@ -471,4 +471,15 @@ class DataListTest extends SapphireTest { $this->assertEquals('Joe', $list->first()->Name, 'First comment should be from Joe'); $this->assertEquals('Phil', $list->last()->Name, 'Last comment should be from Phil'); } + + /** + * + */ + public function testSortByRelation() { + $list = DataList::create("DataObjectTest_TeamComment"); + $list = $list->sort(array('Team.Title' => 'DESC')); + $this->assertEquals(3, $list->count()); + $this->assertEquals(2, $list->first()->TeamID, 'First comment should be for Team 2'); + $this->assertEquals(1, $list->last()->TeamID, 'Last comment should be for Team 1'); + } }