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

Php 在并发请求的情况下会创建重复记录,php,laravel,locking,lumen,Php,Laravel,Locking,Lumen,我有两个表orders和driver\u 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], [

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

在driver\u orders表中使订单id唯一不应该防止订单被分配多次吗?管理员可以通过将以前的driver assigned order状态更改为unassigned来重新分配给另一个驱动程序。因此,使订单唯一并不能解决这个问题。有趣的案例。但从未遇到过类似的问题。您是否尝试将
UNIQUE
索引添加到
driver\u id
列和
order\u id
表上的
driver\u orders
列?well making UNIQUE无法解决此问题,因为管理员可以将这些订单分配给另一个驾驶员或同一个驾驶员,并使以前分配的驾驶员状态未分配。