diff --git a/Cake/ORM/Query.php b/Cake/ORM/Query.php index 0a650fea6d3..11bbf558766 100644 --- a/Cake/ORM/Query.php +++ b/Cake/ORM/Query.php @@ -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); } /** diff --git a/Cake/Test/TestCase/ORM/QueryTest.php b/Cake/Test/TestCase/ORM/QueryTest.php index fcdea6d4cfa..5453369c065 100644 --- a/Cake/Test/TestCase/ORM/QueryTest.php +++ b/Cake/Test/TestCase/ORM/QueryTest.php @@ -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); + } + }