We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

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?



145.0k
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.