Skip to content

Commit 7dd9bea

Browse files
committed
Fix COUNT(*) with group by operations.
Both group by and mapReduce should work with count.
1 parent 711f29e commit 7dd9bea

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

Cake/ORM/Query.php

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -620,17 +620,23 @@ public function first() {
620620
/**
621621
* Return the COUNT(*) for for the query.
622622
*
623-
* This method will replace the selected fields with a COUNT(*)
624-
* erase any configured mapReduce functions and execute the query
625-
* returning the number of rows.
623+
* If the query does not contain GROUP BY or map reduce functions, then
624+
* this method will replace the selected fields with a COUNT(*), and the resulting
625+
* count will be returned.
626+
*
627+
* If the query does contain GROUP BY or map reduce functions, then it
628+
* will be executed, and the number of rows in the ResultSet will be returned.
626629
*
627630
* @return integer
628631
*/
629632
public function count() {
630-
$query = $this->select(['count' => $this->func()->count('*')], true)
631-
->hydrate(false);
632-
$query->mapReduce(null, null, true);
633-
return $query->first()['count'];
633+
if ($this->clause('group') === [] && $this->mapReduce() === []) {
634+
$this->select(['count' => $this->func()->count('*')], true)
635+
->hydrate(false);
636+
return $this->first()['count'];
637+
}
638+
$results = $this->execute();
639+
return count($results);
634640
}
635641

636642
/**

Cake/Test/TestCase/ORM/QueryTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1403,4 +1403,15 @@ public function testCount() {
14031403
$this->assertEquals(['count' => 2], $result->one());
14041404
}
14051405

1406+
/**
1407+
* Test that count() returns correct results with group by.
1408+
*/
1409+
public function testCountWithGroup() {
1410+
$table = TableRegistry::get('articles');
1411+
$query = $table->find('all')
1412+
->group(['published']);
1413+
$result = $query->count();
1414+
$this->assertEquals(1, $result);
1415+
}
1416+
14061417
}

0 commit comments

Comments
 (0)