Reputation: 15742
I would like to know how I can count all records of an entity in a doctrine repository
I found this solution but am not sure if this is good so:
public function findAllCounted()
{
return $this->getEntityManager()
->createQuery('SELECT COUNT(a.id) FROM KSRArticleBundle:Article a')
->getSingleScalarResult();
}
Best Regards, Bodo
Upvotes: 9
Views: 12320
Reputation: 1
the result of the query is an array which always has a position zero and a parameter "1"
$recordnumber= $number[0]["1"];
the table name should be equal to the entity name and start with a capital
Upvotes: 0
Reputation: 1
SQL also allows this:
SELECT COUNT(1) FROM KSRArticleBundle:Article a
In this way the database does not even have to fetch any data from the table, which is even faster. Literally what it says: select the number of the constant '1' for every record. Small speed increase for well-designed data base servers and you dont have to remember anything about the table when writing this.
Upvotes: 0
Reputation: 5040
Just for the record, it is usually better to count on the id :
SELECT COUNT(a.id) FROM KSRArticleBundle:Article a
is a little better
Upvotes: 5
Reputation: 44831
You don't need to count on a specific field, so this will do:
SELECT COUNT(a) FROM KSRArticleBundle:Article a
Upvotes: 11