MINOR DataList::sort() can sort by relation name

This commit is contained in:
Stig Lindqvist 2011-12-18 04:28:09 +01:00
parent 20554b1bf9
commit f59d11c91e
2 changed files with 29 additions and 1 deletions

View File

@ -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
*

View File

@ -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');
}
}