Yii2 how does search() in SearchModel work?
Asked 07 September, 2021
Viewed 1.7K times
  • 51
Votes

Please can someone explain how the search method in a Yii2 SearchModel works? I generated it using Gii. Here it is:

public function search($params){
    $query = MyModel::find();
    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }

    $this->addCondition($query, 'att1');
    $this->addCondition($query, 'att1', true);
    $this->addCondition($query, 'att2');
    $this->addCondition($query, 'att2', true);

    return $dataProvider;
}

This is how I call it:

$search = new MyModelSearch();
$myModels = $search->search(['att3' => '3']);

Regardless of what attributes I use in calling search, I always get back the same result - i.e. all the entries in the table. I'm missing something here that I just do not understand.

Any help would be really appreciated. Thanks.

2 Answer