Laravel Eloquent:从getAttribute函数中获取模型ID?

问题描述 投票:0回答:1

我有一个如下模型:

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;
   }
 }

当我尝试引用此foo属性时,如下所示:

$user = User::find(1);
unset($user->id);   // This line causes the problem.
echo $user->role;

我总是得到“null”而不是预期的“所有者”。

我在这里想念的是什么?

我在laravel 5.5.43中运行它。

following post中,提到了getKey()函数,但是没有用。

问题实际上是由其他原因造成的,如下面的medium post所述。

laravel eloquent accessor getattribute
1个回答
0
投票

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

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

Be Careful to Use Laravel Eloquent’s Accessors, Mutators And Events

© www.soinside.com 2019 - 2024. All rights reserved.