1

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

rji rji
  • 697
  • 3
  • 17
  • 37
  • Double of https://stackoverflow.com/questions/30164491/yii2-subquery-in-active-record – vladnev Feb 08 '18 at 08:30
  • but I don't understend why not ```SELECT project_id, user_ref_id FROM projectsList WHERE user_type_ref_id = 1 AND user_ref_id = yii::$app->user->id``` – vladnev Feb 08 '18 at 08:33
  • 1
    Possible duplicate of [Yii2 subquery in Active Record](https://stackoverflow.com/questions/30164491/yii2-subquery-in-active-record) – vladnev Feb 08 '18 at 08:35

1 Answers1

0

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();
mrateb
  • 2,317
  • 5
  • 27
  • 56