简体   繁体   English

在一个雄辩的Laravel查询中插入/更新多个记录

[英]Insert/Update multiple records in one Eloquent Laravel query

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). 我得到了具有以下关系的“用户和角色”表:$ 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');
}

To update the roles you can try as: 要更新角色,您可以尝试以下方式:

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

It will work for both update and create. 它将同时用于更新和创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM