Laravel雄辩:从getAttribute函数内部获取模型id?

Laravel雄辩:从getAttribute函数内部获取模型id?,laravel,eloquent,accessor,getattribute,Laravel,Eloquent,Accessor,Getattribute,我有一个如下的模型: User extends Authenticatable { protected $appends = array('role'); public function getRoleAttribute() { $role = DB::table('acl_user_has_roles')->where('user_id', $this->id) ->value('role'); r

我有一个如下的模型:

User extends Authenticatable 
{
   protected $appends = array('role');

   public function getRoleAttribute()
   {
      $role = DB::table('acl_user_has_roles')->where('user_id', $this->id)
                ->value('role');
      return $role;
   }
 }
$user = User::find(1);
unset($user->id);   // This line causes the problem.
echo $user->role;
当我尝试引用此foo属性时,如下所示:

User extends Authenticatable 
{
   protected $appends = array('role');

   public function getRoleAttribute()
   {
      $role = DB::table('acl_user_has_roles')->where('user_id', $this->id)
                ->value('role');
      return $role;
   }
 }
$user = User::find(1);
unset($user->id);   // This line causes the problem.
echo $user->role;
我总是得到“null”而不是预期的“Owner”

我错过了什么

我在laravel 5.5.43中运行这个

在中,提到了getKey()函数,但它不起作用


该问题实际上是由其他原因引起的,如下所述。

以防其他人遇到相同的问题。问题是由代码中的另一行引起的。我在echo之前取消设置$user->id

以下中篇文章详细描述了该问题:


您使用的是什么版本的Laravel?很抱歉,忘了提及:Laravel 5.5.43。您的代码似乎没有任何问题。这实际上是你的代码还是你简化了它来回答这个问题?我简化了它来回答这个问题。在实际代码中,我使用$this->id查询另一个表,从中我总是得到null结果,然后最终将问题缩小到$this->id insider getAttribute()总是返回null。$user的其他属性在getAttribute函数中似乎运行良好。您可以添加实际代码吗?我试过你的代码上面,这似乎是工作绝对好。