1

How can I pass two conditions to the method of query which is where? I tried using $query->where($cond[0]), it worked but on $query->where($cond[1]) it gives an error of undefined offset.

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 Answer 1

2

Your $cond variable is creating an array within an array; you're using both array() and shorthand syntax [] (added in PHP 5.4). If you only intend $cond to be a single level array, remove one of the array calls. Either

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

or

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

Sign up to request clarification or add additional context in comments.

6 Comments

Hi! thanks, this fixed the undefined offset but I noticed that the last condition is only evaluated. How can I query both conditions?
Try changing $query->where($cond[0]); to $query->where($cond); and remove the second where call. since you want to query both. $cond[0] or $cond[1] will only pick one of those out of the array.
I tried using $query->where($cond); but it only evaluates the last part, which is on your example is 'last_hard_state' => 2 only
Oh duh, I didnt even see that the keys in the array were the same. The second key is overwriting the first since they're the same, which is only evaluating the last one. Can you tell me what the where clause is supposed to do? WHERE last_hard_state = 0 OR last_hard_state = 2 maybe?
Sure, I'm looking at github.com/yiisoft/yii2/blob/master/docs/guide/… Looks like you can change the array to something like ['or', 'last_hard_state=0', 'last_hard_state=2'] and that should generate last_hard_state = 0 OR last_hard_state = 2
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.