Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel-只返回一个值_Php_Laravel_Eloquent - Fatal编程技术网

Php Laravel-只返回一个值

Php Laravel-只返回一个值,php,laravel,eloquent,Php,Laravel,Eloquent,如何从归属关系返回一个值 这是我的亲戚: public function role() { return $this->belongsToMany('App\Role'); } 现在,当我想访问角色名称时,我必须执行以下操作: Auth::user()->role[0]->name 但我只是想做 Auth::user()->role 但现在我的问题是:“我该怎么做?” 除了问题本身之外,我建议您对belogsToMany关系使用复数名称:这是一种常见的

如何从归属关系返回一个值

这是我的亲戚:

public function role() {

    return $this->belongsToMany('App\Role');

}
现在,当我想访问角色名称时,我必须执行以下操作:

Auth::user()->role[0]->name 
但我只是想做

Auth::user()->role
但现在我的问题是:“我该怎么做?”

除了问题本身之外,我建议您对belogsToMany关系使用复数名称:这是一种常见的最佳实践,使代码更具表达力

public function roles() {
    return $this->belongsToMany('App\Role');
}

Auth::user()->roles()->first()

要执行此操作,您需要按如下方式向用户模型添加自定义属性:

用户模型:

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

是的,这类作品。我现在可以做
Auth::user()->roles()
仍然不太喜欢
()
想要摆脱这些,但是如果真的不可能,我也可以。谢谢。您不能,因为
用户()
并不直接知道
角色的内部内容,因此您需要在那里设置
角色。但是,您可以做的是在
User
类上创建一个方法,该类有一个类似
getRole()
的助手方法。另外,不必使用数组语法获得第一个结果,只需执行
Auth::user()->role()->first()->name
Ah,好的,很好。这正是我所希望的。谢谢
Auth::user()->role