Created
August 6, 2017 03:50
-
-
Save jacksontong/36c269098f00d2c37ccda8fd47eed8ff to your computer and use it in GitHub Desktop.
Yii2 Search model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace app\models\search; | |
use Yii; | |
use yii\base\Model; | |
use yii\data\ActiveDataProvider; | |
use app\models\Customer; | |
use yii\db\Expression; | |
/** | |
* CustomerSearch represents the model behind the search form about `app\models\Customer`. | |
*/ | |
class CustomerSearch extends Customer | |
{ | |
/** | |
* @inheritdoc | |
*/ | |
public function rules() | |
{ | |
return [ | |
[['id'], 'integer'], | |
[['first_name', 'last_name', 'email', 'address', 'created_at', 'updated_at', 'search_full_name'], '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) | |
{ | |
$fullNameExp = new Expression('CONCAT_WS(" ", first_name, last_name)'); | |
$query = Customer::find(); | |
$query->select([ | |
'*', | |
'search_full_name' => $fullNameExp, | |
]); | |
// add conditions that should always apply here | |
$dataProvider = new ActiveDataProvider([ | |
'query' => $query, | |
]); | |
$this->load($params); | |
if (!$this->validate()) { | |
// uncomment the following line if you do not want to return any records when validation fails | |
// $query->where('0=1'); | |
return $dataProvider; | |
} | |
// grid filtering conditions | |
$query->andFilterWhere([ | |
'id' => $this->id, | |
'created_at' => $this->created_at, | |
'updated_at' => $this->updated_at, | |
]); | |
$query->andFilterWhere(['like', 'first_name', $this->first_name]) | |
->andFilterWhere(['like', 'last_name', $this->last_name]) | |
->andFilterWhere(['like', $fullNameExp, $this->search_full_name]) | |
->andFilterWhere(['like', 'email', $this->email]) | |
->andFilterWhere(['like', 'address', $this->address]); | |
return $dataProvider; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment