如何指定用户表中的哪个字段绑定到 CWebUser 的名称属性


How can I specify which field in the user table to be bind to name attribute of the CWebUser?

我发现 yii 可以通过以下方式获取和回显用户名:

    echo Yii::app()->user->name;

我的问题是我如何指定表用户中要与 CWebUser::name 绑定的字段

在你的配置中

// application components
    'components'=>array(
        'user'=>array(
            // enable cookie-based authentication 
            'allowAutoLogin'=>true,
            'class'=>'WebUser',
        ),

WebUser 类(表 "user" 中的 "email" 字段示例):

  class WebUser extends CWebUser
    {
        public function getEmail() 
        {    
            if(!$this->getState('__email')&&$this->id)
            {
                $user = User::model()->findByPk($this->id);
                $this->setState('__email', $user->email);
            }
            $state = $this->getState('__email');
            return $state;
        }
        public function login($identity, $duration=0) 
        {
            $this->allowAutoLogin = true;
            parent::login($identity, $duration);
            $this->id = $identity->id;
            if (!$this->isGuest)
            {
                if($user = User::model()->findByPk($this->id))
                {
                    $this->setState('__email', $user->email);
                }
            }
        }
    }

您应该通过扩展 CUserIdentity 来编写自己的 UserIdentity 组件,并在用户标识声明 $this->username = $user->变量后在 authenticate() 方法中编写

;