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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With