Skip to content

Commit

Permalink
Fix COUNT(*) with group by operations.
Browse files Browse the repository at this point in the history
Both group by and mapReduce should work with count.
  • Loading branch information
markstory committed Nov 21, 2013
1 parent 711f29e commit 7dd9bea
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
20 changes: 13 additions & 7 deletions Cake/ORM/Query.php
Expand Up @@ -620,17 +620,23 @@ public function first() {
/**
* Return the COUNT(*) for for the query.
*
* This method will replace the selected fields with a COUNT(*)
* erase any configured mapReduce functions and execute the query
* returning the number of rows.
* If the query does not contain GROUP BY or map reduce functions, then
* this method will replace the selected fields with a COUNT(*), and the resulting
* count will be returned.
*
* If the query does contain GROUP BY or map reduce functions, then it
* will be executed, and the number of rows in the ResultSet will be returned.
*
* @return integer
*/
public function count() {
$query = $this->select(['count' => $this->func()->count('*')], true)
->hydrate(false);
$query->mapReduce(null, null, true);
return $query->first()['count'];
if ($this->clause('group') === [] && $this->mapReduce() === []) {
$this->select(['count' => $this->func()->count('*')], true)
->hydrate(false);
return $this->first()['count'];
}
$results = $this->execute();
return count($results);
}

/**
Expand Down
11 changes: 11 additions & 0 deletions Cake/Test/TestCase/ORM/QueryTest.php
Expand Up @@ -1403,4 +1403,15 @@ public function testCount() {
$this->assertEquals(['count' => 2], $result->one());
}

/**
* Test that count() returns correct results with group by.
*/
public function testCountWithGroup() {
$table = TableRegistry::get('articles');
$query = $table->find('all')
->group(['published']);
$result = $query->count();
$this->assertEquals(1, $result);
}

}

0 comments on commit 7dd9bea

Please sign in to comment.