Yii2 how does search() in SearchModel work?

前端 未结 2 1526
梦毁少年i
梦毁少年i 2020-12-25 11:57

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

public function         


        
相关标签:
2条回答
  • 2020-12-25 12:21

    If you want some additional param to pass to search() method, you can change search method like this in SomeSearch.php:

    public function search($params, $additional=0)
    {
       //...
       if($additional==1) {
           $query->andWhere(['status'=>['some', 'other']);
       }
    }
    

    and inside controller:

    public function actionIndex()
    {
       $searchModel = new AdminSearch();
    
       $additional=1;
       $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $additional);
    
       return $this->render('index', [
          'searchModel' => $searchModel,
          'dataProvider' => $dataProvider,
       ]);
    }
    
    0 讨论(0)
  • 2020-12-25 12:25

    The search() function generated by Gii use ActiveRecord::load() to set search parameters :

    load() gets the 'FormName' from the model's formName() method (which you may override), unless the $formName parameter is given. If the form name is empty, load() populates the model with the whole of $data, instead of $data['FormName'].

    So you should try :

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

    Or

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

    And of course add a condition on att3 attribute in search() function :

    $this->addCondition($query, 'att3');
    

    But if you really want to use $myModels = $search->search(['att3' => '3']); then you should simply replace $this->load($params) with $this->load($params, '').

    0 讨论(0)
提交回复
热议问题