如何将子查询作为表名传递给yii2中的另一个查询

时间:2018-02-08 07:37:36

标签: yii yii2 yii2-advanced-app yii2-basic-app yii2-model

我有一个查询,我试图转换为yii2语法。以下是查询

 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;

我正在尝试将其转换为yii2格式,如

 $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();

出现错误,如

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

如何将子查询作为表名传递给另一个查询

1 个答案:

答案 0 :(得分:0)

未经测试,但通常情况就是如此。您需要将subQuery作为表传递。因此,请将第二个查询中的->from($subQuery)更改为->from(['subQuery' => $subQuery])

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

然后

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