Search code examples
yii2yii2-basic-appyii2-model

Yii2 passing an array in the FilterWhere Condition


I'm trying to pass array elements in the filter where condition.

getFacilityID() function

 public function getFacilityID()
    {
        $facArray= array();

        $facilityName = Facility::find()->where(['company_id' => \Yii::$app->user->identity->company_id])->all();
        foreach ($facilityName as $facName){
            $facArray[] = $facName->facility_id;
        }  
         //   var_dump($facArray); exit();
            return $facArray;


    }

Here I'm filtering using the getFacilityID() function

 $query->orFilterWhere(['like', 'area_name', $this->area_name])
                ->andFilterWhere(['like', 'facility_id', $this->getfacilityID()]);

The issue is if i have more than 1 facilities it doesn't display any areas.

"->andFilterWhere(['like', 'facility_id', $this->getfacilityID()]); "

The code in bold is causing the issue, if the getfacilityId() has more than 1 array element it doesn't display data in areas. If there is only one element in getFacilityId() it displays the data correctly. Can I get the solution for this??

Thanks in advance..


Solution

  • As Topher mentioned cannot use arrays with like. So changed the query to In condition which worked.

     $query->orFilterWhere(['like', 'area_name', $this->area_name])     
            ->andFilterWhere(['in', 'facility_id', $this->getFacilityID()]);
    

    Read more: http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail