php - 在 Laravel 中,如何在一秒钟内发出并发请求时避免重复记录

标签 php mysql 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;
    }


    }

最佳答案

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

关于php - 在 Laravel 中,如何在一秒钟内发出并发请求时避免重复记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42643834/

相关文章:

php - 简单的 html dom file_get_html 不工作 - 有什么解决方法吗?

mysql - 在 MYSQL 中应用双重条件

php - 为什么我的登录表单允许用户使用正确的用户名登录,但密码不正确? (详见)

javascript - ajax 请求后的 Ajax,以正常方式提交表单

mysql - 拉拉维尔 5 : inserting only if all values exist

php - 无法让 phpseclib 连接 - 错误 10060

javascript - 通过插件在管理页面加载自定义js文件

MySQL 主键为字符串时随机选取1000条记录

caching - Laravel 缓存 Eloquent

javascript - 将值从 js 发布到 php