Retrieval of record count in relational activerecord

I have a question on using relational activerecord. Because self::STAT don’t allow me to query condition like the below code, I used self::MANY_MANY. But have query on retrieve the count of contacts. How do i retrieve the column name by the active record? contactsCount->numofcontacts doesn’t works.

anyone can help?

In Category ActiveRecord:

public function relations()


   return array(





         'condition'=>'??.deleted_time="0000-00-00 00:00:00"',

         'select'=>'COUNT(??.id) AS numofcontacts',




In Controller:


thanks in advance.

Just some thoughts. I haven’t tested it :)

I’d look at it from an SQL perspective. Your approach will create SQL similar to:

SELECT c.*, COUNT( as numofcontacts

FROM category c

LEFT JOIN category-contact cc ON

LEFT JOIN contact co ON AND co.deleted_time="..."

To make this work you need an additional GROUP BY You could create a CDbCriteria for your query and add that there. You’ll also have to add the numofcontacts to the criteria’s select property. See here:

You also have to add numofcontacts as a public property of the Category model, in order for that to be accessible from AR.

yes it works! you just reminded me of the basics i forgotten. Thanks GoofyX and Mike. :D

this works for me: