Starite
Starite

Reputation: 71

Yii2 compare condition in model search

here my search model:

  $query->orFilterWhere(['like', 'name', $this->globalSearch])
        ->orFilterWhere(['like', 'content', $this->globalSearch])
        ->orFilterWhere(['like', 'address', $this->globalSearch]);


    $query->andFilterWhere(['like', 'name', $this->name])
        ->andFilterWhere(['like', 'address', $this->address])
        ->andFilterWhere(['like', 'price', $this->price])      
        ->andFilterWhere(['like', 'gender', $this->gender]);

My search form:

 <?php $form = ActiveForm::begin(['action' => ['results'], 'method' => 'get']); ?>
            <?= $form->field($searchModel, 'globalSearch') ?>  

            <?= $form->field($searchModel, 'gender')->dropDownList(array(''=>'-- Chọn đối tượng muốn tìm --', 'Nam'=>'Nam','Nữ'=>'Nữ', 'Không xác định' => 'Không xác định')) ?>
            <?= $form->field($searchModel, 'address')->dropDownList(array(''=>'-- TP --', 'Hà Nội'=>'Hà Nội','TP.HCM'=>'TP.HCM', 'Đà Nẵng' => 'Đà Nẵng')) ?>

            <div class="form-group">
             <div class="form-group">
    <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
    <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

I've created a dropdownlist for user to filter. But there are a 'price' field, I want to make a dropdown with values like "> 200000" or " < 200000". Is there anyway to change the andFilterWhere(['like', 'price', $this->price]) to maybe '>=' to compare value.

Upvotes: 0

Views: 1282

Answers (1)

Chetan Sharma
Chetan Sharma

Reputation: 2557

You should use

$query->andFilterWhere(['>=', 'price', $this->price]);

or

$query->andFilterWhere(['<=', 'price', $this->price]);

You can also use "between" if you have both values

$query->andFilterWhere(['between', 'price', 10000, 20000]);

Upvotes: 1

Related Questions