简体   繁体   中英

Yii count model with relation

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.

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;

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM