php - 在并发请求的情况下创建重复记录
问题描述
我有两个表orders
和driver_orders
。示例代码是:
DB::beginTransaction();
try{
//check if the order status is pending.If the status is other than pending then one of the driver has accepted the order.
$fetch_order = $this->order->where([
['id',$id],
['status','pending']
])->lockForUpdate()->first();
if(!fetch_order){
throw new Exception('Order is already assigned to another driver.');
}
$driver_id = Auth::id();
//checks if logged in driver has pending order to be delivered.
$check_user_pending_order = $this->driver_order->where([
['driver_id', $driver_id ],
['status','!=','delivered']
])->lockForUpdate()->first();
if($check_user_pending_order){
throw new Exception('You have pending order to be delivered.');
}
$data['order_id'] = $fetch_order->id;
$data['driver_id'] = $driver_id;
$data['amount'] = $fetch_order->amount;
$data['status'] = 'assigned';
//create record in driver_order table
$this->driver_order->create($array);
//update the status in order table
$fetch_order->update([
'status' => 'assigned'
]);
DB::commit();
return response()->json([
'status' => '200',
'message' => 'Order successfully assigned. Get ready to deliver the order.'
]);
}
catch(\Exception $ex){
return response()->json([
'status' => '403',
'message' => $ex->getMessage()
],403);
}
问题是我收到并发请求,这往往会为driver_orders
表中的同一订单创建重复记录。我使用了锁定,但它也不能解决问题。请建议我解决上述问题的方法。
解决方案
推荐阅读
- c++ - 使用 shared_mutex 的内存泄漏
- javascript - 选择使用 javascript es5 更新或推送到数组
- mongodb - OpenShift、MongoDB:无端口转发的连接
- c++ - Arduino TM35 温度传感器错误
- javascript - 无法调用可能未定义的对象
- c# - CheckedListBox 更新checkedItems 很慢
- web-scraping - 如何使用 Scrapy 抓取具有相同解析的多个 URL?
- sql - 带有两个限制语句的请求
- postgresql - 正则表达式替换电话号码中的国家代码和空格
- python - 如何用最后一个非空白单元格填充数据框中的空白单元格?