File tree Expand file tree Collapse file tree 2 files changed +24
-7
lines changed Expand file tree Collapse file tree 2 files changed +24
-7
lines changed Original file line number Diff line number Diff line change @@ -620,17 +620,23 @@ public function first() {
620
620
/**
621
621
* Return the COUNT(*) for for the query.
622
622
*
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.
626
629
*
627
630
* @return integer
628
631
*/
629
632
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 );
634
640
}
635
641
636
642
/**
Original file line number Diff line number Diff line change @@ -1403,4 +1403,15 @@ public function testCount() {
1403
1403
$ this ->assertEquals (['count ' => 2 ], $ result ->one ());
1404
1404
}
1405
1405
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
+
1406
1417
}
You can’t perform that action at this time.
0 commit comments