2016-10-29 19:19
浏览 169

在一个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) {
        //send email to user to reset the password

    flash('Great!! User was updated', 'success');
    return redirect('users');

图片转代码服务由CSDN问答提供 功能建议

使用角色创建和更新来处理新用户的最简洁方法是什么? 我得到了用户和角色表 关系:$ this-> belongsToMany(Role :: class)。 当我创建一个新用户时,我想以相同的形式分配角色,但角色将被添加到不同的表中。 同样,当我更新用户时,也许我会添加一个额外的角色,或者我可能需要删除一些角色,在更新场景中,我需要查看表中有哪些角色并将其与表单同步 data。 Below是一个更新用户和角色信息的功能。 用户更新有效但角色更新不起作用。 最干净的代码是什么: 创建具有一个或多个角色的新用户并更新用户信息并同步角色信息。

 公共功能更新($ id,Requests \ CreateUserRequest $ request){
 $ user = User :: findOrFail($ id); 
 $ user-> name  = $ request-> name; 
 $ user-> email = $ request-> email; 
 if($ request-> resetPassword)
 $ user-> password = null; \  n //向用户发送电子邮件以重置密码
 $ user-> save(); 
 $ roles = Role :: sync($ request-> roles); 
 $ roles->  user() - > update($ user-> id); 
 // $ user-> update($ request-> all()); 
 flash('很棒!!用户已更新 ','成功'); 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongping6974 2016-10-29 19:26

    To update the roles you can try as:


    It will work for both update and create.

    打赏 评论

相关推荐 更多相似问题