5

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.

teone
  • 2,153
  • 3
  • 25
  • 49

3 Answers3

6

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;
shgnInc
  • 2,054
  • 1
  • 23
  • 34
0

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"
Daniel Vaquero
  • 1,315
  • 1
  • 8
  • 13
  • Hi, maybe I've explained wrong, I don't need to know how many "Annunci" are inerted for one "Azienda", but how many "Azienda" have at least one "Annunci". How can I achieve this? – teone Sep 19 '13 at 12:14
  • oohh, i'm sorry. I edited my answer. does this solve your question? – Daniel Vaquero Sep 19 '13 at 12:35
0

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

pszaba
  • 1,034
  • 9
  • 16
  • Maybe I've explained wrong. This method will return the related record(s) of the current record. Instead I would like to count how many record (Aziende) have at least one relation (Annunci). Thanks anyway. – teone Sep 19 '13 at 12:07