title: Yii accessing relational data from Yii::app->user
body: <p><strong>I would like to know whether it is possible or if there is a easier way to do this.</strong></p>
  
  <p>On many pages i'd like to use the relational data, now every page i use it i place the following code:</p>
  
  <pre><code>&lt;?php
      if(!Yii::app()-&gt;user-&gt;isGuest){
          $user = User::model()-&gt;findByPk(Yii::app()-&gt;user-&gt;id);
      }
  ?&gt;
  </code></pre>
  
  <p>So I can use the following in the view:</p>
  
  <pre><code>$user-&gt;account-&gt;name
  </code></pre>
  
  <p>To display current users related account's name</p>
  
  <p>It would be nice if I could just do the following:</p>
  
  <pre><code>Yii::app-&gt;user-&gt;account-&gt;name
  </code></pre>
  
  <p>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.</p>
  
  <pre><code> Solution
  
   |
   |
   |
   V
  </code></pre>
  
  <p><strong>Solution</strong></p>
  
  <p>I combined the good of both answers to create the following:</p>
  
  <pre><code>class WebUser extends CWebUser {
  private $_user;
  
  public function getAccount(){
      if(!$this-&gt;isGuest &amp;&amp; (!isset($this-&gt;_user) || Yii::app()-&gt;user-&gt;id != $this-&gt;_user-&gt;id)){
          $this-&gt;_user = User::model()-&gt;findByPk(Yii::app()-&gt;user-&gt;id);
      }
      if(!empty($this-&gt;_user)){
          return $this-&gt;_user-&gt;account;
      } else {
          return false;
      }
  
    }
  }
  </code></pre>
  
  <p>So now I can use the following:</p>
  
  <pre><code>Yii::app()-&gt;user-&gt;account-&gt;name
  </code></pre>
  
  <p>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.</p>
  
  <p>Place it in Components and be sure to add the part Afnan talks about to the config (main.php)</p>
  
  <p><em>I accept the answer of Afnan because it helped me most (The part I needed to know)</em></p>