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.

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

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services