Yii Set Default Sort Order in Model

2020-04-11 05:48发布

问题:

I create a web app with Yii with the yii-user extension. At user listing page, display the user list was ordered by create_at.

I want to display the user list order by username.

This is original code:

 public function search()
    {
        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('password',$this->password);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('activkey',$this->activkey);
        $criteria->compare('create_at',$this->create_at);
        $criteria->compare('lastvisit_at',$this->lastvisit_at);
        $criteria->compare('superuser',$this->superuser);
        $criteria->compare('status',$this->status);

        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'pagination'=>array(
                'pageSize'=>Yii::app()->getModule('user')->user_page_size,
            ),
        ));
    }

I added this code.

$criteria->order = "username ASC";

After adding, the user list is only sorting by username whatever the header is clicked.

How can I set the default sort order?

回答1:

Use the sort property:

return new CActiveDataProvider(get_class($this), array(
    'criteria' => $criteria,
    'sort' => array(
        'defaultOrder' => 'username ASC', 
    ),
));