diff --git a/model/SQLQuery.php b/model/SQLQuery.php index c1c0e5b3f..85a2b241b 100644 --- a/model/SQLQuery.php +++ b/model/SQLQuery.php @@ -1038,8 +1038,13 @@ class SQLQuery { * @return int */ public function count( $column = null) { + // we can't clear the select if we're relying on its output by a HAVING clause + if(!empty($this->having)) { + $records = $this->execute(); + return $records->numRecords(); + } // Choose a default column - if($column == null) { + elseif($column == null) { if($this->groupby) { $column = 'DISTINCT ' . implode(", ", $this->groupby); } else { diff --git a/tests/model/SQLQueryTest.php b/tests/model/SQLQueryTest.php index 12cf229f7..42a4f42e0 100755 --- a/tests/model/SQLQueryTest.php +++ b/tests/model/SQLQueryTest.php @@ -7,7 +7,22 @@ class SQLQueryTest extends SapphireTest { protected $extraDataObjects = array( 'SQLQueryTest_DO', ); - + + public function testCount() { + + //basic counting + $qry = SQLQueryTest_DO::get()->dataQuery()->getFinalisedQuery(); + $qry->setGroupBy('Common'); + $ids = $this->allFixtureIDs('SQLQueryTest_DO'); + $this->assertEquals(count($ids), $qry->count('"SQLQueryTest_DO"."ID"')); + + //test with `having` + if (DB::getConn() instanceof MySQLDatabase) { + $qry->setHaving('"Date" > 2012-02-01'); + $this->assertEquals(1, $qry->count('"SQLQueryTest_DO"."ID"')); + } + } + public function testEmptyQueryReturnsNothing() { $query = new SQLQuery(); $this->assertEquals('', $query->sql());