From 613a25aa4f614e48a7cd982eeff73e2dd4b35371 Mon Sep 17 00:00:00 2001 From: mark_story Date: Fri, 15 Nov 2013 22:09:08 -0500 Subject: [PATCH] Add total() to ORM\Query. This method makes it much easier to get COUNT(*) for queries. This will make removing paginateCount() from PaginatorComponent. --- Cake/ORM/Query.php | 14 ++++++++++++++ Cake/Test/TestCase/ORM/QueryTest.php | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/Cake/ORM/Query.php b/Cake/ORM/Query.php index 64c64c39dd7..313eb5611f5 100644 --- a/Cake/ORM/Query.php +++ b/Cake/ORM/Query.php @@ -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. * diff --git a/Cake/Test/TestCase/ORM/QueryTest.php b/Cake/Test/TestCase/ORM/QueryTest.php index 63f9549d226..5234645e974 100644 --- a/Cake/Test/TestCase/ORM/QueryTest.php +++ b/Cake/Test/TestCase/ORM/QueryTest.php @@ -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()); + } + }