根据用户 ID 检查记录是否已存在,如果存在,则更新,如果不存在则插入 - 使用 Laravel



我正在尝试针对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();
}

你可以让它更容易

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

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

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

firstOrCreate()firstOrNew()的区别:

  • firstOrCreate()将自动在 数据库(如果未找到匹配项)。否则它会给你 匹配的项目。
  • firstOrNew()将为您提供一个新的模型实例,以便在以下情况下使用 未找到匹配项,但仅在以下情况下保存到数据库 你显式地这样做(在模型上调用 save()。 否则它 会给你匹配的项目。

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

发件人:第一个或创建

最新更新