10

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
}
Community
  • 1
  • 1
chrismacp
  • 3,834
  • 1
  • 30
  • 37

1 Answers1

20

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

rojoca
  • 11,040
  • 4
  • 45
  • 46
  • Ah nice, I'll check that out right away. I'm actually only using Doctrine 2.0 as well so will probably need to update my code as well. – chrismacp Dec 14 '11 at 21:10
  • 1
    I just recognized that you can directly use count($house->getRooms()). This will correctly add a single COUNT query. Also see: http://stackoverflow.com/questions/15645911/doctrine-extra-lazy-load-doesnt-work-as-expected-with-count – webDEVILopers Jun 29 '15 at 13:43
  • What would be the best way to add a WHERE into this? i.e., count rooms where capacity > 2, or similar? Struggling on this. – Jacob Manser May 02 '17 at 16:12
  • @JacobManser I am no longer up to date with doctrine but it looks like you can find an answer here: http://docs.doctrine-project.org/en/latest/reference/working-with-associations.html#filtering-collections – rojoca May 03 '17 at 07:41