Search code examples
phpyii2yii2-model

How to do use nested condition in AndWhere in yii2


Before marking as duplicate question,kindly read it. I have different problem here. I want to generate this kind of Query using yii2 search model.

select * from t1 innerjoin t2 on (t1.id = t2.id) where ((t1.price >= '1000' and t1.price <= '5000') OR 
                   ( t2.price >= '1000' and t2.price <= '5000' ))

Joining is not a problem here. The main problem is the where clause. I tried this but not working.

$query->andFilterWhere([
                     'and',
                     ['>=', 't1.price', $this>start_price],
                     ['<=', 't1.price', $this->end_price]
                 ])
      ->orFilterWhere([
                      'and',
                       ['>=', 't2.price', $this->start_price],
                       ['<=', 't2.price', $this->end_price]
              ]);

Solution

  • Try

    $query->andFilterWhere([
        'or',
        [
            'and',
            ['>=', 't1.price', $this>start_price],
            ['<=', 't1.price', $this->end_price]
        ],
        [
            'and',
            ['>=', 't2.price', $this->start_price],
            ['<=', 't2.price', $this->end_price]
        ]
    ]);