Skip to content

Commit

Permalink
Add total() to ORM\Query.
Browse files Browse the repository at this point in the history
This method makes it much easier to get COUNT(*) for queries. This will
make removing paginateCount() from PaginatorComponent.
  • Loading branch information
markstory committed Nov 16, 2013
1 parent 759dfeb commit 613a25a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
14 changes: 14 additions & 0 deletions Cake/ORM/Query.php
Expand Up @@ -616,6 +616,20 @@ public function first() {
return $this->_results->one();
}

/**
* Return the COUNT(*) for for the query.
*
* This method will replace the selected fields with a COUNT(*)
* and execute the queries returning the number of rows.
*
* @return integer
*/
public function total() {
return $this->select(['count' => $this->count('*')], true)
->hydrate(false)
->first()['count'];
}

/**
* Toggle hydrating entites.
*
Expand Down
19 changes: 19 additions & 0 deletions Cake/Test/TestCase/ORM/QueryTest.php
Expand Up @@ -1351,4 +1351,23 @@ public function testHydrateBelongsToCustomEntity() {
$this->assertInstanceOf($authorEntity, $first->author);
}

/**
* Test getting totals from queries.
*
* @return void
*/
public function testTotal() {
$table = TableRegistry::get('articles');
$result = $table->find('all')->total();
$this->assertEquals(3, $result);

$query = $table->find('all')
->where(['id >' => 1]);
$result = $query->total();
$this->assertEquals(2, $result);

$result = $query->execute();
$this->assertEquals(['count' => 2], $result->one());
}

}

0 comments on commit 613a25a

Please sign in to comment.