Reputation: 2183
I have a model Aziende, that is related (1:N) to anther model called Annunci, like this:
'annunci' => array(self::HAS_MANY,'Annunci','azienda_id'),
I would like to count how many record does really have this relation, in mySql I will do:
SELECT count( * )
FROM `aziende` a
JOIN annunci an ON an.azienda_id = a.id
How can i do this with Yii AR Model?
PS: I tried to look out conditional query, but i can't find my way.
Upvotes: 5
Views: 4829
Reputation: 2196
In Yii relation type, we have STAT which do this for you. In relations():
'annunciCount' => array(self::STAT,'Annunci','azienda_id'),
and in controller:
$model= Model::model()->findAll();
echo 'The Number is: '.$model->annunciCount;
Upvotes: 6
Reputation: 1305
Edited:
$criteria = new CDbCriteria();
$criteria->condition = 'annunci.id IS NOT null';
$aziendeList= Aziende::model()->with('annunci')->findAll($criteria);
$count = count($aziendeList); // Count how many "Azienda" have at least one "Annunci"
Upvotes: 0
Reputation: 1064
Have you tried the
getRelated()
From Yii api:
Returns the related record(s). This method will return the related record(s) of the current record. If the relation is HAS_ONE or BELONGS_TO, it will return a single object or null if the object does not exist. If the relation is HAS_MANY or MANY_MANY, it will return an array of objects or an empty array.
You can just use the "count($related)" or "sizeOf($related)" to get the count.
Yii api link:
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#getRelated-detail
Upvotes: 0