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(

      'contactsCount'=>array(

         self::MANY_MANY,

         'Contact',

         'category-contact(category_id,contact_id)',

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

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

      ),

   ),

}



In Controller:




print_r(Category::model()->findByPk(1)->contactsCount);



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(co.id) as numofcontacts

FROM category c

LEFT JOIN category-contact cc ON cc.category_id=c.id

LEFT JOIN contact co ON cc.contact_id=co.id AND co.deleted_time="..."



To make this work you need an additional GROUP BY c.id. 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:

http://www.yiiframework.com/forum/index.php?/topic/3776-find-and-some-additinal-columns/page__view__findpost__p__21256

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:


count($category->contacts)