【问题标题】:check if record is already exist against user id and update if exist and insert if not exist - using laravel根据用户 ID 检查记录是否已经存在,如果存在则更新,如果不存在则插入 - 使用 laravel
【发布时间】:2019-11-20 21:40:46
【问题描述】:

如果 user_id 已经存在,我正在尝试更新记录,如果在 laravel 中的 user_id 不存在,则插入新记录:

但我的用户 ID 在 $doctorProfile['user_id'] 数据正在插入,但用户 id 插入为 NULL:

我的控制器代码:

          if($request->has('doctor_profile'))
        {
            $doctorProfile = $body['doctor_profile'];


                 $data_array = [

                'user_id' => $doctorProfile['user_id'],
                'medical_credentials' => 
               $doctorProfile['medical_credentials'],
                'registration_number' => 
           $doctorProfile['registration_number'],
                'registration_expiration_date' => 
          $doctorProfile['registration_expiration_date'],
                'dea_number' => $doctorProfile['dea_number'],
                'dea_expiration_date' => 
       $doctorProfile['dea_expiration_date'],
                'dea_issue_date' => $doctorProfile['dea_issue_date'],
                'npi_number' => $doctorProfile['npi_number'],
                'billing_title' => $doctorProfile['billing_title'],
                'billing_employment_type' => 
       $doctorProfile['billing_employment_type'],
                'other_employment_type' => $doctorProfile['other_employment_type'],
                'nadean_number' => $doctorProfile['nadean_number'],
                'upin' => $doctorProfile['upin'],
                'wcb_authorization' => $doctorProfile['wcb_authorization'],
                'wcb_rating_code' => $doctorProfile['wcb_rating_code'],
                'wcb_date_of_issue' => $doctorProfile['wcb_date_of_issue'],
                'hospital_privileges' => $doctorProfile['hospital_privileges'],
            ];

            $medId = MedicalIdentifiers::firstOrCreate(['user_id' => $doctorProfile['user_id']], $data_array);
            $medId->save();

        }

【问题讨论】:

  • 如果在调用 firstOrCreate 之前转储 $data_array,会得到什么?像 dd($data_array);?你能给我们看看数据吗
  • 你在哪里声明$body变量?您能告诉我们请求的结构吗?

标签: php laravel authentication


【解决方案1】:

你可以让它变得更容易

 if($request->has('doctor_profile'))
     MedicalIdentifiers::firstOrCreate($request->all());

firstOrCreate() 检查在它之前存在的所有参数finds 匹配。如果不是所有参数都匹配,则将创建模型的新实例。

如果您只想检查特定字段,请使用 firstOrCreate(['field_name' => 'value']) 并仅在数组中添加一项。这将返回第一个匹配的项目,如果没有找到匹配项,则创建一个新项目。

firstOrCreate()firstOrNew()的区别:

  • firstOrCreate() 会自动在 如果没有找到匹配的数据库。否则它会给你 匹配的项目。
  • firstOrNew() 会给你一个新的模型实例来使用 if 未找到匹配项,但仅在以下情况下才会保存到数据库中 您明确地这样做(在模型上调用 save() )。否则它 会给你匹配的项目。

在其中一个或另一个之间进行选择取决于您想要做什么。如果您想在第一次保存模型实例之前对其进行修改(例如设置名称或某些必填字段),您应该使用firstOrNew()。如果你可以直接使用参数在数据库中创建一个新的模型实例而不需要修改它,你可以使用firstOrCreate()。

来自:First Or Create

【讨论】:

    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2016-01-06
    • 2010-12-10
    • 1970-01-01
    • 2021-03-29
    相关资源
    最近更新 更多