1
秒內請幫我找出問題。如何避免重複記錄併發請求在Laravel
有時(並不總是)我的下面的代碼在數據庫中插入兩條記錄(到用戶表和配置文件表中),但是我在插入之前檢查「mobile_no」已經存在,或者沒有做出唯一的手機號碼基於記錄。
static function postData($data) {
try {
if (isset($data['number'])) {
//exist
$exist = Profile::where('mobile_no', '=', $data['number'])->get();
//print_r($exist);
if (count($exist) > 0) {
$user = User::find($exist[0]['user_id']);
if (isset($data['last_name'])) {
$user->first_name = $data['first_name'];
}
if (isset($data['last_name'])) {
$user->last_name = $data['last_name'];
}
if (isset($data['email'])) {
$user->email = $data['email'];
}
$user->save();
$proid = $exist[0]['user_id'];
$profile_result = Profile::find($proid);
if (isset($data['number'])) {
$profile_result->mobile_no = $data['number'];
}
if (isset($data['birthday'])) {
$profile_result->dob = $data['birthday'];
}
$profile_result->save();
return $exist[0]['user_id'];
}else{
$user = new User();
if (isset($data['first_name'])) {
$user->first_name = $data['first_name'];
}
if (isset($data['last_name'])) {
$user->last_name = $data['last_name'];
}
$user->save();
$id = $user->id;
$profile = new Profile();
$profile->user_id = $id;
if (isset($data['mobile_number'])) {
$profile->mobile_no = $data['number'];
}
if (isset($data['birthday'])) {
$profile->dob = $data['birthday'];
}
$profile->save();
$proid = $profile->user_id;
$profile_result = $profile::where('user_id', '=', $proid)->get();
$user_result = $user::where('id', '=', $id)->get();
$output = array();
return (string) $id;
}
}
} catch (Exception $ex)
{
return $ex;
}
}