用户模型:
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token', 'role_id',
];
protected $appends = [
'role',
];
public function getRoleAttribute()
{
return $this->role->name;
}
/**
* User role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function role()
{
return $this->belongsTo('App\Role');
}
}
我不想显示角色的名称而不是角色ID .
但它说:
User.php第38行中的ErrorException:未定义属性:App \ User :: $ role
角色表包含 id 和 name
users表包含 role_id
Edit:
当我尝试 return $this->role()->name;
它给了我一个:
User.php第38行中的ErrorException:未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ name
但我检查角色,这有效...
/**
* Check if the user is an admin.
*
* @return bool
*/
public function isAdmin()
{
if ($this->role->name == 'admin') {
return true;
}
return false;
}
2 回答
这是因为你有 role 属性和 role 关系,尝试重命名其中一个,它将与
return $this->role->name;
一起使用使用关系,而不是属性: