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

incorrect output while concatenating query based on if condition yii2


I have a query as below

 $query= (new Query())->select(['title'])
               ->from('projects')
               ->join('LEFT JOIN', 'user AS u', 'p.user_ref_id=u.user_id')
               ->where('p.created_date >= STR_TO_DATE('.'"'.$fmonth.'"'.', "%d-%b-%Y")')
               ->andWhere('p.created_date <= DATE_ADD(STR_TO_DATE('.'"'.$tmonth.'"'.', "%d-%b-%Y"), INTERVAL 1 DAY)')->all();

if I print the variable $query, I am getting below output

   Array ( [0] => Array ( [title] => test project 1))

But if I write the below code

  $query= (new Query())->select(['title'])
               ->from('projects AS p')
               ->join('LEFT JOIN', 'user AS u', 'p.user_ref_id=u.user_id')
               ->where('p.created_date >= STR_TO_DATE('.'"'.$fmonth.'"'.', "%d-%b-%Y")')
               ->andWhere('p.created_date <= DATE_ADD(STR_TO_DATE('.'"'.$tmonth.'"'.', "%d-%b-%Y"), INTERVAL 1 DAY)');
 if(!empty($status)){
  $query->andWhere(['p.project_status' => 1]);
 }
 $query->all();

When I print $query for above code. The output I am getting is

 yii\db\Query Object ( [select] => Array ( [0] => p.title [1]) [selectOption] => [distinct] => [from] => Array ( [0] => projects AS p ) [join] => Array ( [0] => Array ( [0] => LEFT JOIN [1] => user AS u [2] => p.user_ref_id=u.user_id) )....

Why am I getting this object/array format when I try to split the query and concatenate. Is there any other way to execute to get in similar format as

  Array ( [0] => Array ( [title] => test project 1))

Solution

  • If I understand correctly in first case you are printing the result of all() method while in the second one you are printing the Query object because there all() is not called on the printed variable but rather on the object itself so the result is lost.

    If you print $query->all() in second case you will get what you want.