原文链接: 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属性了