Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 590
teone Avatar asked Sep 19 '13 11:09

teone


1 Answers

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;
like image 158
shgnInc Avatar answered Sep 28 '22 21:09

shgnInc