【发布时间】:2023-04-09 09:59:01
【问题描述】:
用户模型:
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
用户表包含一个role_id
编辑:
当我尝试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;
}
【问题讨论】:
标签: php laravel laravel-eloquent