【问题标题】:How to avoid duplicated records when concurrent requests make within a second in Laravel如何在 Laravel 中在一秒钟内发出并发请求时避免重复记录
【发布时间】:2017-03-07 08:49:58
【问题描述】:

请帮我找出问题。

有时(并非总是)我的以下代码会在 DB 中插入两条记录(到用户表和配置文件表中),但我在插入“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;
    }


    }

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    对数据库使用索引UNIQUE,它将为您处理。请记住在尝试插入重复键时正确处理错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-07
      相关资源
      最近更新 更多