Laravel 5.6中多对多关系的正确更新,存储和删除方式

时间:2018-08-02 12:45:05

标签: laravel laravel-5 laravel-5.6

我有这段代码,可以存储和更新,但我不知道如何通过detach方法删除用户的角色。如何从多个用户角色中删除一个角色?我不确定roles()->attach()行中的代码,而且我认为你们对此有更好的解决方案。

UsersController:

public function store(Request $request)
{

    if($request->isMethod('put'))
    {
        $user = User::findOrFail($request->id);
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $role = Role::where('name',$request->input('role_id'))->first();
        $user->roles()->attach($role->id);
    }
    else
    {
        $user = new User;
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->password = Hash::make($request->input('password'));
        $user->remember_token = str_random(40);
        $user->id = User::count() + 1; //get the last user id? for pivot table
        $user->roles()->attach(2); //default role (2) : admin is (1)
    }

    if($user->save()){
        return response()->json($user);
    }
}

User.php

  public function roles(){
      return $this->belongsToMany('App\Role');
  }

Role.php

  public function users(){
      return $this->belongsToMany('App\User');
  }

数据透视表

   Schema::create('role_user', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('role_id')->unsigned();
   });

1 个答案:

答案 0 :(得分:1)

一种方法(并不是说这是正确的方法)是使用sync方法(同步关联)。

我用表格创建一个下拉列表。
我在模型中有一个函数可以执行以下操作;

public function selectListValues($key, $value, $where=[])
{

    $list = [];

    if (is_array($value)) {

        array_unshift($value, $key);
        $result = $this->model->where($where)->get($value);

        foreach ($result->toArray() as $r) {
            $index = $r[$key];
            unset($r[$key]);
            $list[$index] = implode(' ', $r);
        }

    } else {

        try {
            $result = $this->model->where($where)->get()->pluck($value, $key);
            $list = $result->toArray();
        } catch(ModelNotFoundException $e){
            return null;
        }

    }

    return $list;

}
我在生成表格的函数中调用

$roles = $roleModel->selectListValues('id', 'name');

然后在控制器的我的存储方法中

$roles = $request->get('roles');

$collection = new Collection();

foreach ($roles as $role) {
    try {
        $collection->add(Role::where('id', '=', $role)->firstOrFail());
    } catch (\Exception $e) {
        dd($e);
    }
}

if (empty($collection)) {
    throw new \Exception('No roles found for '.$user->email);
}

$user->roles()->sync($collection);