Laravel-雄辩地只返回一个值 [英] Laravel - Eloquent return only one value
本文介绍了Laravel-雄辩地只返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何从belongsToMany关系中返回一个值。
How can I return one value from a belongsToMany relation.
这是我的关系:
public function role() {
return $this->belongsToMany('App\Role');
}
现在,当我想访问角色名称时,我必须请执行以下操作:
Now when I want to access the Role Name I have to do the folowing:
Auth::user()->role[0]->name
但是我只是想做
Auth::user()->role
但现在我的问题是:我该怎么办?
But now my question is: "How can I do that?"
推荐答案
为此,您需要向用户模型添加自定义属性,如下所示:
to do this you need add custom attribute to user model as the following:
用户模型:
protected $appends = ['role']; // add new attribute to user model
public function getRoleAttribute()
{
return $this->roles->first(); // don't use roles() it would execute every time
}
public function roles() {
return $this->belongsToMany('App\Role');
}
现在可以使用
Auth::user()->role
这篇关于Laravel-雄辩地只返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文