Skip to content

Commit

Permalink
Making Query::count() return consistent results. It was trying to be too
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lorenzo committed Jan 24, 2014
1 parent 73b9bed commit 9f8505f
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions src/ORM/Query.php
Expand Up @@ -868,18 +868,22 @@ public function first() {
/** /**
* Return the COUNT(*) for for the query. * 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 * @return integer
*/ */
public function count() { public function count() {
$query = clone $this; $query = clone $this;
$query->select(['count' => $this->func()->count('*')])->hydrate(false); $query->limit(null);
$query->mapReduce(null, null, true);
$query->formatResults(null, true); // Forcing at least one field to be selected
return (int)$query->first()['count']; $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;
} }


/** /**
Expand Down

0 comments on commit 9f8505f

Please sign in to comment.