duanbarong4321 2012-11-03 14:57
浏览 106

Yii从Yii :: app-> user访问关系数据

I would like to know whether it is possible or if there is a easier way to do this.

On many pages i'd like to use the relational data, now every page i use it i place the following code:

        $user = User::model()->findByPk(Yii::app()->user->id);

So I can use the following in the view:


To display current users related account's name

It would be nice if I could just do the following:


Set state isn't what i'm looking for since it's not only the account name i want to use, and I don't want to add a state for all relational data I might want to use.




I combined the good of both answers to create the following:

class WebUser extends CWebUser {
private $_user;

public function getAccount(){
    if(!$this->isGuest && (!isset($this->_user) || Yii::app()->user->id != $this->_user->id)){
        $this->_user = User::model()->findByPk(Yii::app()->user->id);
        return $this->_user->account;
    } else {
        return false;


So now I can use the following:


The above method retrieves the data if the user is logged in and there is no data stored or the user has a different id.

Place it in Components and be sure to add the part Afnan talks about to the config (main.php)

I accept the answer of Afnan because it helped me most (The part I needed to know)

  • 写回答

3条回答 默认 最新

  • duanke6057 2012-11-03 19:53

    Well i do not know if it is the best solution but i usually do things like this by extending CWebUser

    What i would do is create file in Components folder that extends CWebUser

    class CWebUserExtend extends CWebUser
         * @return the type of user based on forien key of UserType
        public function getUserAccname()
            $user = User::model()->findByPk(yii::app()->user->id);
            if ($user === null)
                return 'error';            
                return $user->account->name;            

    and in main.php file modify 'User' index in following manner

                // enable cookie-based authentication
                            'class'=>'CWebUserExtend',//class that extends CWebUser

    This would allow you to do something


    Hope it helps

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 App的会员连续扣费
  • ¥15 不同数据类型的特征融合应该怎么做
  • ¥15 用proteus软件设计一个基于8086微处理器的简易温度计
  • ¥15 用联想小新14Pro
  • ¥15 multisim中关于74ls192n和DSWPK开关仿真图分析(减法计数器)
  • ¥15 基于8255的交通灯设计
  • ¥15 w3wp,exe 中发生未处理的 Microsoft ,NETFramework 异常。
  • ¥20 C51单片机程序及仿真(加减器)
  • ¥15 AQWA | 水动力分析 二阶波浪力
  • ¥15 c语言题目:成绩管理系统