如何更改使用一个字段的搜索模型

How to change search model for using one field

我已经生成了 CRUD bu Gii。默认情况下,应用程序中的搜索对每个 table 列使用一个字段。我应该如何更改我的搜索模型,以便通过单独的字段在所有列中进行搜索?

这是我的模型:

class UserSearch extends User
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'auth_key', 'password_hash', 'password_reset_token', 'email'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = User::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'username', $this->username])
            ->andFilterWhere(['like', 'auth_key', $this->auth_key])
            ->andFilterWhere(['like', 'password_hash', $this->password_hash])
            ->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
            ->andFilterWhere(['like', 'email', $this->email]);

        return $dataProvider;
    }
}

我是这样做的:

 public function search($params)
    {
        ..............................
        if($this->keyword) {
            if(preg_match("/[A-Za-z]+/", $this->keyword) == true) {
                $query->andFilterWhere(['like', 'LOWER(CONCAT(name, age, WHATEVERFIELDS)), ', strtolower($this->keyword)]);
            } else {
                $query->andFilterWhere(['id' => $this->keyword]);
            }            
        }

关键字实际上并不是数据库中的一列,它只是我附加到搜索模型的一个变量。如果关键字是数字我认为它是一个 ID,如果你愿意,你可以忽略这部分。否则我会连接一些字段并在结果中搜索。您也可以不连接字段,只为每个字段添加一个条件,由您决定。

您可以在以下位置查看完整文件:https://github.com/Mihai-P/yii2-core/blob/master/models/ContactSearch.php