Larvale MySQL事务回退、悲观锁
use Illuminate\Support\Facades\DB;
try{
DB::transaction(function () use ($data) {
# 获取用户信息,加悲观锁,其他的不可读写
$userInfo = UserProfile::query()->where(['uid' => $data['apprentice_uid']])->lockForUpdate()->first(); # 加锁
# 第一个sql操作
User::query()->where(['id' => 1])->increment('exchange_coupon', 10);
throw new \Exception('异常,回退');
# 第二个sql操作
$TradeHistory = new TradeHistory();
$TradeHistory->is_pay = Config::$TRUE;
$TradeHistory->save();
# 第三个sql操作
$Apprentice = new Apprentice();
$Apprentice->is_send = $data['is_send'];
$Apprentice->save();
return true;
});
}catch (\Throwable $ex){
return false;
}