Aipo
Aipo

Reputation: 1985

How to write count(*) SQL in DQL, Doctrine ORM

How to get count of rows in database by id? SELECT count(*) FROM members; Without performance issues. What are ways to write this query using entityManager? I am using php version 5.6 and symfony 3

Upvotes: 2

Views: 1987

Answers (2)

rkeet
rkeet

Reputation: 3468

Edit: Just saw Gregoire's answer. That will work. However, if you already have the Entity which has the relation, and it's initialized, the below would allow you to get this info without an additional query to the DB.


You could use the association and get it from the Collection (see Working with Associations in the docs

class SomeEntity
{
    /**
     * @var Collection|Member[]
     */
    protected $members;

    // other properties

    // PHP >= 7 -> public function countMembers(): int
    public function countMembers()
    {
        return $this->getMembers()->count();
    }

    // PHP >= 7 -> public function getMembers(): Collection
    public function getMembers()
    {
        return $this->members;
    }

    // other getters/setters
}

Upvotes: 3

Gregoire Ducharme
Gregoire Ducharme

Reputation: 1106

You have to use your EntityRepository Add a function in it and write something like this:

$queryBuilder = $this->_em->createQueryBuilder()
        ->select('COUNT(e)')
        ->from('AppBundle:Entity', 'e');

    return $queryBuilder->getQuery()->getSingleScalarResult();

Upvotes: 3

Related Questions