原文鏈接: http://www.yiichina.com/tutorial/120
在這添加另一種排序功能,即
1、創建子類繼承\yii\db\ActiveRecord類, 並重寫attributes()函數,之後所有的model類全部繼承自定義的ActiveRecord類
/**
* 關聯表屬性,判定哪些關聯表字段需要排序
* @var unknown
*/
static $relationAttributes = ['customer_name' => 'table.name'];
public function attributes(){
$attributes = parent::attributes();
if(static::$relationAttributes){
foreach (static::$relationAttributes as $key => $attribute){
if(is_number($key){
$attributes[] = $attribute;
}else{
$attributes[$key] = $attribute;
}
}
}
return $attributes;
}
2、創建\yii\data\ActiveDataProvider子類
在構造函數中添加
$modelClass = $config['query']->modelClass; $model = new $modelClass(); $sortAttributes = []; foreach ($model->attributes() as $key => $attribute) { if(is_numeric($key)){ $sortAttributes[$attribute] = [ 'asc' => [$attribute => SORT_ASC], 'desc' => [$attribute => SORT_DESC], 'label' => $model->getAttributeLabel($attribute), ]; }else{ $sortAttributes[$key] = [ 'asc' => [$attribute => SORT_ASC], 'desc' => [$attribute => SORT_DESC], 'label' => $model->getAttributeLabel($attribute), ]; } } $config['sort']['attributes'] = $sortAttributes; parent::__construct($config);
通過上述設置,就是讓顯示的字段和數據庫字段做一個映射,也就不用在search()函數中設置setSort。
2、不寫label
public function attributeLabels(){
return [
...........
'customer_name'=>'自定義名',
......
];
}
這樣就不用到處添加label屬性了