Search code examples
yiiyii2yii2-advanced-appyii2-basic-appyii2-model

how to use subquery inside select statement of yii2


I have a query as below.

 $subQuery = (new Query())->select('is_approved')->from('user_requests')->where(['user_ref_id' => yii::$app->user->id])->andWhere(['AND','project_ref_id = p.project_id']);

This is the subquery which I am trying to call in select statement as below

 $Query = (new Query())->select(['project_id','IF(p.project_type_ref_id = 2, '.$subQuery.', "" ) AS project_request_id'])
                             ->from('projects AS p');

If I try to execute the query I am getting below error in the line where I added $subQuery

PHP Recoverable Error – yii\base\ErrorException
Object of class yii\db\Query could not be converted to string

How to add a subquery in select statement. Please help. Thanks in advance !!


Solution

  • Since you want to use first query as pure string add

    ->createCommand()->rawSql;
    

    to it. This generates SQL statement out of Query object.