douchen2025 2016-08-04 12:36
浏览 395
已采纳

Laravel:批量分配插入新记录或更新现有[重复]

This question already has an answer here:

I have a User model and a UserInfo model. they are a one to one relationship.

When a user signs up, he then goes ahead to fill a very large form with more info. That is contained in the user_info table, represented by UserInfo model.

I currently do this

$user->user_info()->create($request->all());

it works but if it is run the second time, it creates andother UserInfo record for the same user.

Is there a way i can do it so that if the UserInfo record already exists for this user, it only updtes the exisiting one

Is there a method like updateOrCreate that can work with Mass Assignment like this?

So that if the UserInfo record already exist on this User, it just updates with these new values

</div>
  • 写回答

1条回答 默认 最新

  • dongniaocheng3773 2016-08-04 12:52
    关注

    You can achieve updateOrCreate functionality by using updateOrCreate() method.
    Usage:

    Model::updateOrCreate(
       ['primary_key' => 8],
       ['field' => 'value', 'another_field' => 'another value']
    );
    

    In your case, you can use fit in following way:

    $user->user_info()->updateOrCreate(['id'=>$user->id],$request->all());
    

    In place of id in ['id'=>$user->id] use the name of your model's primary key.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看