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

时间:2015-02-27 04:36:32

标签: search crud yii2

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

那是我的模特:

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;
    }
}

1 个答案:

答案 0 :(得分:1)

我就是这样做的:

 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