Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 How to pass a range to search model

Tags:

php

model

yii2

I need to search a range for a field. How do I apply a between or greater than/less than statement to the search model.

Something similar to this. However those attributes aren't valid in the Search Model

$params['MlsSearch']['min_price'] = 10;
$params['MlsSearch']['max_price'] = 100;

$searchModel = new ModelSearch();
$dataProvider = $searchModel->search($params);
like image 570
pjhagel Avatar asked Aug 14 '14 21:08

pjhagel


2 Answers

1) Define attributes in the model.

class ModelSearch extends Model
{
     public $min_price;
     public $max_price;

    /*....*/
}

2) Make attributes safe

public function rules()
{
    return [
         /*... */
         [['min_price', 'max_price', ], 'safe'],
    ]
}

3) Modify Search Function

public function search($params)
{
    /*... */
    $query->andFilterWhere(['>', 'price', $this->min_price]);
    $query->andFilterWhere(['<', 'price', $this->max_price]);
    /*... */
}
like image 128
pjhagel Avatar answered Oct 21 '22 09:10

pjhagel


You can also use BETWEEN construction:

$query->andFilterWhere(['between', 'price', $this->min_price, $this->max_price]);
like image 35
user103751 Avatar answered Oct 21 '22 11:10

user103751