Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Count related objects via ORM

Is it possible to count related objects without selecting all of them? Now possible is:

$user->getAddresses()->count()

However ORM selects every addresses related to user and then count them. I would like to only execute:

SELECT count() FROM...

is it possible somehow with ORM?



107.3k
Accepted
answer
edited Dec '15

Yes it is:

Address::findFirst(array(
    'columns'=>array('count(user) as count')
    'conditions'=>'user = :user:',
    'bind'=>['user'=>$user->getId()]
));

Of course where Address is your Address class and user is correct column.