[英]Yii CDbCriteria select row based on count of another table
I have a posts table and a users table. 我有一个职位表和一个用户表。 Posts are linked to Users using an authorId column in posts table. 帖子使用帖子表中的authorId列链接到用户。 I want to select those users with at least one or more posts using CDbCriteria for a CGridView. 我想使用CDbCriteria为CGridView选择具有至少一个或多个帖子的用户。 Below is the sql query that I am trying to implement. 下面是我要实现的sql查询。
SELECT *
FROM user
WHERE ID IN
(SELECT creatorId FROM video GROUP BY creatorId HAVING count(*) > 0)
This is what I have tried so far. 到目前为止,这是我尝试过的。
$criteria=new CDbCriteria;
$criteria->with = array('videoCount');
$criteria->addCondition('t.status=1');
$criteria->addCondition('videoCount>0');
This doesn't work because the 'videoCount' is a relation. 这是行不通的,因为“ videoCount”是一个关系。
How do I accomplish this? 我该如何完成? I am using Yii 1.1.15. 我正在使用Yii 1.1.15。
Try using the query builder if you could as it will be much easy 如果可以的话, 请尝试使用查询生成器 ,因为这很容易
$query = Yii::app()->db->createCommand()
->select()
->from('user')
->where(array('in','ID', Yii::app()->db->createCommand()
->select('creatorId')
->from('video')
->group('creatorId')
->having('count(*) > 0')->queryColumn()))
->queryAll();
This will execute the required query ie 这将执行所需的查询,即
SELECT * FROM `user` WHERE `ID` IN ('SELECT `creatorId` FROM `video` GROUP BY `creatorId` HAVING count(*) > 0')
Update 更新
If you want to stick with CDbCriteria then you can try this 如果您想坚持使用CDbCriteria ,可以尝试一下
$criteria = new CDbCriteria();
$criteria->addCondition('ID IN (SELECT creatorId FROM video GROUP BY creatorId HAVING count(*) > 0)');
Note:- I haven't tested this criteria but hopefully it will work. 注意:-我尚未测试此标准,但希望它会起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.