1

我正在尝试在过滤器 where 条件中传递数组元素。

getFacilityID() 函数

 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;


    }

在这里,我使用getFacilityID()函数进行过滤

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

问题是如果我有超过 1 个设施,它不会显示任何区域。

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

粗体代码导致问题,如果 getfacilityId() 有超过 1 个数组元素,它不会在区域中显示数据。如果 getFacilityId() 中只有一个元素,它会正确显示数据。我可以得到这个解决方案吗?

提前致谢..

4

2 回答 2

2

正如Topher提到的,不能将数组与 like 一起使用。因此将查询更改为有效的条件。

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

阅读更多:http ://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#where()-detail

于 2016-07-13T11:47:51.060 回答
2

试试这个代码:

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

这是我的例子

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

结果查询是:

SELECT 
    *
FROM
    `user`
WHERE
    ((`username` LIKE '%a1%')
        OR (`username` LIKE '%b1%'))
        AND (`email` LIKE '%someEmail%')
于 2016-07-13T12:17:07.277 回答