Yii2 在模型搜索中比较条件

Yii2 compare condition in model search

这是我的搜索模型:

  $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]);

我的搜索表单:

 <?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']) ?>

我创建了一个下拉列表供用户筛选。但是有一个 'price' 字段,我想用“> 200000”或“< 200000”这样的值制作一个下拉列表。 无论如何要将 andFilterWhere(['like', 'price', $this->price]) 更改为 '>=' 以比较值。

你应该使用

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

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

如果你有两个值,你也可以使用 "between"

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