diff --git a/model/DataList.php b/model/DataList.php index ff9f92b7e..e55c0a2f3 100644 --- a/model/DataList.php +++ b/model/DataList.php @@ -223,7 +223,18 @@ class DataList extends ViewableData implements SS_List, SS_Filterable, SS_Sortab $query->limit($limit, $offset); }); } - + + /** + * Return a new DataList instance with distinct records or not + * + * @param bool $value + */ + public function distinct($value) { + return $this->alterDataQuery(function($query) use ($value){ + $query->distinct($value); + }); + } + /** * Return a new DataList instance as a copy of this data list with the sort * order set. diff --git a/model/DataQuery.php b/model/DataQuery.php index 8b5b5e612..801546974 100644 --- a/model/DataQuery.php +++ b/model/DataQuery.php @@ -549,6 +549,17 @@ class DataQuery { return $this; } + /** + * Set whether this query should be distinct or not. + * + * @param bool $value + * @return DataQuery + */ + public function distinct($value) { + $this->query->setDistinct($value); + return $this; + } + /** * Add an INNER JOIN clause to this query. * diff --git a/tests/model/DataListTest.php b/tests/model/DataListTest.php index 2c647260a..cf907c86d 100755 --- a/tests/model/DataListTest.php +++ b/tests/model/DataListTest.php @@ -121,7 +121,18 @@ class DataListTest extends SapphireTest { // $check = $list->limit(null, 2); // $this->assertEquals(1, $check->count()); } - + + public function testDistinct() { + $list = DataObjectTest_TeamComment::get(); + $this->assertContains('SELECT DISTINCT', $list->dataQuery()->sql(), 'Query is set as distinct by default'); + + $list = $list->distinct(false); + $this->assertNotContains('SELECT DISTINCT', $list->dataQuery()->sql(), 'Query does not contain distinct'); + + $list = $list->distinct(true); + $this->assertContains('SELECT DISTINCT', $list->dataQuery()->sql(), 'Query contains distinct'); + } + public function testDataClass() { $list = DataObjectTest_TeamComment::get(); $this->assertEquals('DataObjectTest_TeamComment',$list->dataClass()); diff --git a/tests/model/DataQueryTest.php b/tests/model/DataQueryTest.php index b76f6fdd1..f29d8a8d4 100644 --- a/tests/model/DataQueryTest.php +++ b/tests/model/DataQueryTest.php @@ -155,6 +155,18 @@ class DataQueryTest extends SapphireTest { $result = $query->column('Title'); $this->assertEquals(array('First', 'Second', 'Last'), $result); } + + public function testDistinct() { + $query = new DataQuery('DataQueryTest_E'); + $this->assertContains('SELECT DISTINCT', $query->sql(), 'Query is set as distinct by default'); + + $query = $query->distinct(false); + $this->assertNotContains('SELECT DISTINCT', $query->sql(), 'Query does not contain distinct'); + + $query = $query->distinct(true); + $this->assertContains('SELECT DISTINCT', $query->sql(), 'Query contains distinct'); + } + }