Yii2:使用一个字段搜索多列

Mou*_*nho 2 php yii2

我有一个名为的表calls,我需要一个搜索输入,以在两列中搜索,contact_number并且contact_name. 我如何在 Yii2 上执行此操作?

_search.php

$form->field($model, 'searchstring')->textInput(['placeholder' => 'Search']); 
Run Code Online (Sandbox Code Playgroud)

common\models\CallsSearch.php

[['searchstring'], 'safe']

(..)

$query->orFilterWhere(['like', 'searchstring', $this->contact_name])
   ->orFilterWhere(['like', 'searchstring', $this->contact_number]);
Run Code Online (Sandbox Code Playgroud)

controllers\CallsController.php

public function actionIndex()
{
    $searchModel = new CallsSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
}
Run Code Online (Sandbox Code Playgroud)

Muh*_*lam 7

好吧,您正在尝试使用search_string输入来过滤 2 个字段contact_name,或者contact_number但您没有使用它来与字段进行比较,您将自定义模型属性指定为table_column,这是错误的,您应该将搜索模型代码更改为以下内容

 $query->andFilterWhere ( [ 'OR' ,
            [ 'like' , 'contact_name' , $this->search_string ],
            [ 'like' , 'contact_number' , $this->search_string ],
        ] );
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你。