Youcef04 Youcef04 - 1 year ago 205
PHP Question

Sub-queries ActiveRecord Yii

Is it possible to make sub-queries in ActiveRecord in Yii?

i have a query like this:

select * from table1
where table1.field1 in (select table2.field2 from table2)

i'm currently using the fallowing code:

object1::model()->findAll(array('condition'=>'t.field1 in (select table2.field2 from table2)'))


i would like to know if there is a manner to construct the sub-query without using SQL, and without using joins.

Is there any solution ?

and thanks in advance.

Answer Source

First find doublets by db fields:

$model=new MyModel('search');

$criteria=new CDbCriteria();
$criteria->group = 'col1,col2,col3';
$criteria->having = 'COUNT(col1) > 1 AND COUNT(col2) > 1 AND COUNT(col3) > 1';

Get the subquery:


Add the subquery condition:

$mainCriteria=new CDbCriteria();
$mainCriteria->condition=' (col1,col2,col3) in ('.$subQuery.') ';
$mainCriteria->order = 'col1,col2,col3';

How to use:

$result = MyModel::model()->findAll($mainCriteria);


$dataProvider = new CActiveDataProvider('MyModel', array(


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download