在并发请求的情况下创建重复记录

时间:2018-07-10 16:39:52

标签: php laravel locking lumen

我有两个表ordersdriver_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表中为同一顺序创建重复记录。我使用了锁定,但它也不能解决问题。请为我建议解决上述问题的方法。

0 个答案:

没有答案