From 9f8505fb8302eb20f0b8024465297836d3600df2 Mon Sep 17 00:00:00 2001 From: Jose Lorenzo Rodriguez Date: Thu, 23 Jan 2014 18:21:49 +0100 Subject: [PATCH] Making Query::count() return consistent results. It was trying to be too smart on what it needed to return. In some cases it returned the total rows found and in other cases the total rows fetched. Having a consisten result. This method, while very mariginally slower, will always return the correct result. --- src/ORM/Query.php | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/ORM/Query.php b/src/ORM/Query.php index a88c1a0b5f6..fc2c6a52231 100644 --- a/src/ORM/Query.php +++ b/src/ORM/Query.php @@ -868,18 +868,22 @@ public function first() { /** * Return the COUNT(*) for for the query. * - * 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. - * * @return integer */ public function count() { $query = clone $this; - $query->select(['count' => $this->func()->count('*')])->hydrate(false); - $query->mapReduce(null, null, true); - $query->formatResults(null, true); - return (int)$query->first()['count']; + $query->limit(null); + + // Forcing at least one field to be selected + $query->select($query->newExpr()->add('1')); + $statement = $this->connection()->newQuery() + ->select(['count' => $query->func()->count('*')]) + ->from(['source' => $query]) + ->execute(); + $result = $statement->fetch('assoc')['count']; + + $statement->closeCursor(); + return (int)$result; } /**