How to solve ambiguous column in where clause?

I have a search query in Yii2 something like this:


public function search($params)

        {

            $query = Post::find();

            $dataProvider = new ActiveDataProvider([

                'query' => $query,

            ]);

            $this->load($params);

            if (!$this->validate()) {

                   return $dataProvider;

               }


               if(strlen($this->group_id) >= 1){

                   $query->joinWith(['group'=>function($query){

                       $query->from(Group::tableName().' c1');

                   }], true, 'INNER JOIN')

                         ->andWhere(['like', 'c1.title', $this->group_id]);

               }


               $query->andFilterWhere(['like', 'title', $this->title]);

               return $dataProvider;

            }

       }

The idea is that, searching in grid table Yii2, is working if i search for them separately, but it’s giving following error if i search together:


Error Info: Array

(

    [0] => 23000

    [1] => 1052

    [2] => Column 'title' in where clause is ambiguous

)

Query looks like this:


SELECT COUNT(*) FROM `posts` INNER JOIN `groups` `c1` ON `posts`.`post_id` = `c1`.`post_id` WHERE (`c1`.`title` LIKE '%free%') AND (`title` LIKE '%test%')

Any idea for how to solve this ?

Maybe try

$query->andFilterWhere([‘like’, ‘t.title’, $this->title]);

How could this ever work? what is t in reference to ?

As far as I know, you need to name the other ‘title’ as well - (c2.title ?)

Answer to this problem is by adding alias to the $query:


 $query = Post::find()->alias('a1');

and then :


$query->andFilterWhere(['like', 'a1.title', $this->title])

Thanks all!

2 Likes