我正在尝试执行一些相互依赖的查询,所以我想要的是如果发生任何错误,则回滚事务内的所有查询。到目前为止我尝试过的是
DB::transaction(function () use($user,$token,$request) {
$billing = User_billings::create([
'users_id' => $user->id,
'agent_id' => null,
'purpose' => 'Some Purpose',
'agent_token_id'=>$token->id,
'amount' => $request->amount,
'payment_method' => 'Agent Token',
'status' => 1
]);
if($billing){
$user_jorunal = User_journal::create([
'bill2_id' => $billing->id, //Intentionally made this error to test transaction, this should be 'bill_id'
'u_id' => $user->id,
'purpose' => 'Topup via Agent Token',
'debit' => $billing->amount,
'invoice_number' => time()
]);
if($user_jorunal){
if($this->agentTokenBalance($request->token_id) == 0){
$token->status=1;
$token->update();
}
return response()->json(['status'=>true,'message'=>'TopUp was Successful!']);
}
}
});
因此,当我执行此查询时,它会生成一个错误 SQLSTATE[HY000]: General error: 1364 Field 'bill_id' does not have a default value
,但它还会在 user_billings 上创建一行 table 。
你能指出我错在哪里吗?
all of the above code is running fine, be sure that there is no logical error in query except the intentional one . I am using laravel 5.7 in this project
PHP version is 7.2.19
following laravel documentation
最佳答案
手动使用事务
使用DB::beginTransaction();
开始事务。
在每次错误后使用DB::rollBack();
。
交易确认时使用DB::commit();
。 ;
laravel reference
关于php - 如何使用 Laravel 事务回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65213149/