How to pass subquery as table name to another quer

2019-08-17 18:07发布

问题:

I have a query which I am trying to convert into yii2 syntax. Below is the query

 SELECT project_id, user_ref_id FROM 
            (
            SELECT `project_id`, `user_ref_id`
            FROM `projectsList` 
            WHERE user_type_ref_id = 1) AS a WHERE user_ref_id = '.yii::$app->user->id;

I am trying to convert it into yii2 format like

 $subQuery = (new Query())->select(['p.project_id', 'p.user_ref_id'])->from('projectsList')->where(['user_type_ref_id' => 1]);

 $uQuery = (new Query())->select(['p.project_id', 'p.user_ref_id'])->from($subQuery)->where(['user_ref_id ' => yii::$app->user->id])->all();

It is giving an error like

 trim() expects parameter 1 to be string, object given

How to I pass subquery as table name to another query

回答1:

Not tested, but generally this is how it goes. You need to pass the subQuery as a table. So change ->from($subQuery) in the second query to ->from(['subQuery' => $subQuery])

$subQuery = (new Query())->select(['p.project_id', 'p.user_ref_id'])->from('projectsList')->where(['user_type_ref_id' => 1]);

Then

 $query = (new Query())->select(['p.project_id', 'p.user_ref_id'])->from(['subQuery' => $subQuery])->where(['subQuery.user_ref_id ' => yii::$app->user->id])->all();