【问题标题】:BadMethodCallException with message 'Method save does not exist.'带有消息“方法保存不存在”的 BadMethodCallException。
【发布时间】:2018-03-24 06:38:09
【问题描述】:

我不明白为什么我有这个错误,我刚刚创建了assigneRole和权限,但是assigneRole不起作用,当我使用它时它说同步或保存不存在,我认为它一定是因为WhereName,有什么想法吗?

这是我的用户模型:

 public function roles()
  {
      return $this->belongsToMany(Role::class);
  }

public function assignRole($role)
{
    return $this->roles->save(
        Role::whereName($role)->firstOrFail()
    );


terminal php artisan tinker

$user = User::latest()->first();

$user->assignRole('editor');
}

【问题讨论】:

  • 如果是这样的话,那么这个方法 public function givePermissionTo(Permission $permission) { return $this->permissions()->save($permission); } 应该不起作用,但它确实起作用。
  • 对不起,我解释得很糟糕,请参阅答案。
  • 这是一个很好的解决方案,谢谢我的朋友。
  • 不客气 :)

标签: php laravel


【解决方案1】:

您是否尝试将 () 添加到 $this->roles 以使 $this->roles()?

$this->roles 返回一个结果 $this->roles() 返回模型关系。

$this->roles$this->roles() 有区别,请参阅此帖Difference between method calls $model->relation(); and $model->relation;

【讨论】:

  • 谢谢伙计,问题是,我看了 2 年前的视频,laravel 5.1,我只是假设代码已经过时或刚刚停止,他们最近一直在这样做,所以我没有重要的细节。
猜你喜欢
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多