1
votes

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

2
Possible duplicate of yii2 ActiveQuery 'OR LIKE' filtertopher
You can't use like with arrays hence the possible duplicate.topher
Thanks Buddy... got it solved!!!Mohan Prasad

2 Answers

2
votes

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

2
votes

try this code:

        if(null != $this->getFacilityID())
            foreach ($this->getfacilityID() as $key => $id) {
                $query->orFilterWhere(['like', 'facility_id', $id]);
            }
        $query->andFilterWhere(['like', 'area_name', $this->area_name]);
        $query->all();

Here is my example

        foreach (['a1','b1'] as $key => $value) {
            $q->orFilterWhere(['like', 'username', $value]);
        }
        $q->andFilterWhere(['like', 'email', 'someEmail']);
        $q->all();

and result query is :

SELECT 
    *
FROM
    `user`
WHERE
    ((`username` LIKE '%a1%')
        OR (`username` LIKE '%b1%'))
        AND (`email` LIKE '%someEmail%')