laravel:Macroable.php 第 74 行中的 BadMethodCallException:方法分离不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38864242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:17:03  来源:igfitidea点击:

laravel : BadMethodCallException in Macroable.php line 74: Method detach does not exist

phplaravellaravel-5laravel-5.2

提问by Ijaz Khan

I have three tables

我有三张桌子

  • users
  • groups
  • group_user(a pivot table which handles the membership of users in groups)
  • users
  • groups
  • group_user(处理组中用户成员资格的数据透视表)

I am trying to delete the membership of a user from a group like this:

我正在尝试从这样的组中删除用户的成员资格:

public function userDelete (Request $request, $userId)
{
    $gid = $request->group;
    $group = Group::find($gid);
    $user = User::find($userId);

    $user->groups->detach();

    // and the second method is :
    // foreach ($group->users as $user) {
    //     if ($user->pivot->user_id == $userId) {
    //         $user->detach($gid);
    //         
    //         break;
    //     }
    // }
}

I have tried it in may ways, but it always gives the error that the method detach()is not found:

我已经尝试了多种方法,但它总是给出detach()找不到该方法的错误:

BadMethodCallException in Macroable.php line 74: Method detach does not exist.

Macroable.php 第 74 行中的 BadMethodCallException:方法分离不存在。

回答by jedrzej.kurylo

When you do $user->groups->detach(), you call detach()on the resulting groups collection.

当您执行$user->groups->detach() 时,您对生成的组集合调用detach()

Instead, you should call the detach()method on the relation:

相反,您应该在关系上调用detach()方法:

$user->groups()->detach();