Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently count related rows within a model using Doctrine2

Tags:

doctrine-orm

I'm pretty new to Doctrine and wondering how to efficiently calculate the number of related objects there are for a particular model object.

I read here that it's not a great idea to use the entity manager within models so I'm wondering how I would query the database to find out without lazy loading all of the related models and doing a count().

I haven't really found a great answer yet, but it seems like this is a pretty fundamental thing?

For example

class House
{
    /**
     * @var Room
     */
    protected $rooms

    public function getRoomCount()
    {
        // Cant use entity manager here?
    }
}

class Room
{
    // Shed loads of stuff in here
}
like image 961
chrismacp Avatar asked Dec 14 '11 18:12

chrismacp


1 Answers

Doctrine 2 will get counts for you automatically as association properties are actually Doctrine Collection objects:

public function getRoomCount() 
{
    return $this->rooms->count();
}

If you mark the association as eager, Doctrine will load the rooms whenever you query for house entities. If you mark them as lazy (the default), Doctrine won't load the rooms until you actually access the $this->rooms property.

As of Doctrine 2.1 you can mark associations as extra lazy. This means that calling $this->rooms->count() won't load the rooms, it will just issue a COUNT query to the database.

You can read about extra lazy collections here: http://www.doctrine-project.org/docs/orm/2.1/en/tutorials/extra-lazy-associations.html

like image 62
rojoca Avatar answered Oct 20 '22 11:10

rojoca