[英]Yii count model with relation
I have a model Aziende, that is related (1:N) to anther model called Annunci, like this: 我有一个模型Aziende,它与称为Annunci的花药模型相关(1:N),如下所示:
'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: 我想算一下有多少记录确实有这种关系,在mySql中我会做:
SELECT count( * )
FROM `aziende` a
JOIN annunci an ON an.azienda_id = a.id
How can i do this with Yii AR Model? 我怎么能用Yii AR模型做到这一点?
PS: I tried to look out conditional query, but i can't find my way. PS:我试图找出条件查询,但我找不到自己的方式。
In Yii relation type, we have STAT which do this for you. 在Yii关系类型中,我们有STAT为您执行此操作。 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: 来自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.
如果关系是HAS_ONE或BELONGS_TO,则它将返回单个对象,如果该对象不存在,则返回null。 If the relation is HAS_MANY or MANY_MANY, it will return an array of objects or an empty array.
如果关系是HAS_MANY或MANY_MANY,它将返回一个对象数组或一个空数组。
You can just use the "count($related)" or "sizeOf($related)" to get the count. 你可以使用“count($ related)”或“sizeOf($ related)”来计算。
Yii api link: Yii api链接:
http://www.yiiframework.com/doc/api/1.1/CActiveRecord#getRelated-detail http://www.yiiframework.com/doc/api/1.1/CActiveRecord#getRelated-detail
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.