简体   繁体   中英

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 eg 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM