在Laravel模型中重用关系

在Laravel模型中重用关系

问题描述:

I am having issues with laravel 4 that did not happen with 3.

In the Permissions_Role model I have this relationship set up.

/**
 * User Relationship
 *
 * @return User
 */
 public function user()
 {
     return $this->belongsTo('User', 'user_id');
 }

Now, I want to use it later in the model to get that user's username. In laravel 3 this could be done with the following.

return ucword($this->user()->first()->username);

However, in four, it does not seem to return an object the same way and I can't seem to figure out the new syntax for it. Below is what I am trying currently.

/**
 * Get username
 *
 * @return string
 */
 public function getUsernameAttribute()
 {
     return ucwords($this->user()->first()->username);
 }

Any help on this would be greatly appreciated. Thanks :)

我遇到laravel 4的问题,但没有发生在3. p>

在Permissions_Role模型中,我建立了这种关系。 p>

  / ** 
 * User Relationship 
 * 
 * @return User 
 * / 
 public  function user()
 {
返回$ this-> belongsTo('User','user_id'); 
} 
  code>  pre> 
 
 

现在,我想要 稍后在模型中使用它来获取该用户的用户名。 在laravel 3中,这可以通过以下方式完成。 p>

  return ucword($ this-> user() - > first() - > username); 
   code>  pre> 
 
 

然而,在四,它似乎没有以相同的方式返回一个对象,我似乎无法弄清楚它的新语法。 以下是我目前正在尝试的内容。 p>

  / ** 
 *获取用户名
 * 
 * @return string 
 * / 
 n public function getUsernameAttribute()  
 {
返回ucwords($ this-> user() - > first() - > username); 
} 
  code>  pre> 
 
 

任何帮助 对此我将不胜感激。 谢谢:) p> div>

You dont have to write () anymore, its automaticly castet into a property

new: $this->user->username instead of $this->user()->username