Search code examples
phpmysqlyii2yii2-model

how can i use variable in where condition ( in clause) in yii2


I am trying to filter user records from user table. I have a user_id string like e.g. 7,8,9, its working fine when I put that user_id string directly in when condition like this

 $model =  User::find()
            ->select(['id','username','first_name','last_name','image','year','city'])
            ->distinct(true)
            ->where(['IN','id',[ 7,8,9 ]])
            ->asArray()
            ->all();

but when I pass this user_id string in a variable, its show me only one record,

     $userFiltr = ArrayHelper::getColumn($result,'user_id');
     $user_id =  implode(',',$userFiltr); // $user_id return 7,8,9

     $model =  User::find()
        ->select(['id','username','first_name','last_name','image','year','city'])
        ->where(['IN','id',[ $user_id ]]) // when is user this variable $user_id, then query return only one result, white if i put 7,8,9 directly in where(['IN','id',[ 7,8,9 ]]) it return correct result  
        ->asArray()
        ->all();

problem is that when is user this variable $user_id, then query return only one result, white if i put 7,8,9 directly in where(['IN','id',[ 7,8,9 ]]) it return correct result .

how can i use variable in where condition like where(['IN','id',[ $user_id ]]) please help,thanks in advance


Solution

  • As $userFiltr is already an array, pass it to where:

    $userFiltr = ArrayHelper::getColumn($result,'user_id');
    
    $model = User::find()
        ->select(['id','username','first_name','last_name','image','year','city'])
        ->where(['IN','id',$userFiltr])
        ->asArray()->all();