dousi1906 2016-10-29 19:19
浏览 194
已采纳

在一个Eloquent Laravel查询中插入/更新多个记录

What would be the cleanest way to process new user with roles creation and update? I got Users and Roles tables with relationships: $this->belongsToMany(Role::class). When I am creating a new user, in the same form I would like to assign role(s), but roles will be added into different table. And the same for when I would update the user, maybe I will add a additional role or I maybe I will need to remove some roles, In update scenario I would need to see what roles there are in the table and sync that with the form data. Below is a function updating user and Role information. The user update works but the Role update doesn't. What would the cleanest code to: Create a new user with one or more roles and to update user information and sync the role information.

public function update($id, Requests\CreateUserRequest $request) {
    $user=User::findOrFail($id);
    $user->name=$request->name;
    $user->email=$request->email;
    if($request->resetPassword)
    {
        $user->password=null;
        //send email to user to reset the password
    }
    $user->save();
    $roles=Role::sync($request->roles);
    $roles->user()->update($user->id);

    //$user->update($request->all());
    flash('Great!! User was updated', 'success');
    return redirect('users');
}
  • 写回答

1条回答 默认 最新

  • dongping6974 2016-10-29 19:26
    关注

    To update the roles you can try as:

    $user->save();
    $user->roles()->sync($request->roles);
    

    It will work for both update and create.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题