No, there is no way to programmatically build a subquery using Yii CDbCriteria and CActiveRecord . This is not like Query Builder .
You can still make subqueries in several ways:
$results = Object1::model()->findAll(array( 'condition'=>'t.field1 in (select table2.field2 from table2)') );
You can also make a join (which is likely to be faster, subqueries may be slow):
$results = Object1::model()->findAll(array( 'join'=>'JOIN table2 ON t.field1 = table2.field2' );
You can also make a direct SQL query with findAllBySql :
$results = Object1::model()->findAllBySql(' select * from table1 where table1.field1 in (select table2.field2 from table2)' );
However, you can at least provide a nice AR-style interface like this:
class MyModel extends CActiveRecord { public function getResults() { return Object1::model()->findAll(array( 'condition'=>'t.field1 in (select table2.field2 from table2)') ); } }
Called like this:
$model = new MyModel(); $results = $model->results;
One interesting alternative idea is to create your subquery using Query Builder CDbCommand or something else, and then just pass the resulting SQL query string to CDbCritera addInCondition()
? Not sure if this will work, but may:
$sql = Yii::app()->db->createCommand() ->select('*') ->from('tbl_user') ->text; $criteria->addInCondition('columnName',$sql);
You can always extend the base CDbCriteria class to process and assemble subqueries anyway. You can make a good extension that you could release! :)
I hope this helps!
thaddeusmt
source share