【发布时间】:2023-04-03 08:51:02
【问题描述】:
我有一个用户模型,在模型中我有一个名为 role_id 的整数字段。如果我回显该值 {{ $user->role_id }} 我会得到一个数字,我也会在用户模型与角色模型上建立关系,但如果我尝试执行 {{ $user->role()->role_name }} 我会收到以下错误:
Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$role_name
如果我使用代码{!! \App\Models\Role::whereKey($user->role_id)->pluck('role_name') !!},我得到的值是正确的,所以它与我看不到它在哪里的关系有关。
用户模型
public function role()
{
return $this->hasOne('\App\Models\Role');
}
榜样
class Role extends Model
{ 使用软删除;
public $table = 'roles';
const CREATED_AT = null;
const UPDATED_AT = null;
protected $dates = ['deleted_at'];
public $fillable = [
'role_name'
];
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'id' => 'integer',
'role_name' => 'string'
];
/**
* Validation rules
*
* @var array
*/
public static $rules = [
];
public function users(){
return $this->belongsTo('App\Models\User');
}
【问题讨论】:
标签: php relationships laravel-5.6