传递一个条件数组来查询Yii2中的方法

时间:2015-12-23 01:12:27

标签: php yii2

如何将两个条件传递给query where的方法?我尝试使用$query->where($cond[0]),它有效,但在$query->where($cond[1])上,它给出了未定义偏移量的错误。

public function search($params, $cond)
{
    $query = ServiceStatuses::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => ['defaultOrder' => ['last_hard_state' => SORT_DESC]],
    ]);

    $this->load($params);

    .
    .
    .

    $query->where($cond[0]);      //<<<<----- This works
    $query->where($cond[1]);      //<<<<----- Undefined offset: 1

    return $dataProvider;
}

public function searchIncidents($params)
{
    $cond = array (['last_hard_state' => 0, 'last_hard_state' => 2]);
    $dataProvider = $this->search($params, $cond);
    return $dataProvider;
}

1 个答案:

答案 0 :(得分:2)

您的$cond变量正在数组中创建一个数组;您正在使用array()和速记语法[](在PHP 5.4中添加)。如果您只想将$cond作为单级数组,请删除其中一个数组调用。任

$cond = ['last_hard_state' => 0, 'last_hard_state' => 2];

$cond = array('last_hard_state' => 0, 'last_hard_state' => 2);