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',
),
),
}
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: