php - 如何使用 Laravel 事务回滚

标签 php mysql laravel laravel-5 eloquent

我正在尝试执行一些相互依赖的查询,所以我想要的是如果发生任何错误,则回滚事务内的所有查询。到目前为止我尝试过的是


        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/

相关文章:

php - 在mysql字段中使用php变量

php - 使用表单在 MySQL DB 中存储和检索关联数组

PHP-当数组数量不知道时如何合并数组,因为通过循环获取数组

php - Laravel 5.2 更新数据库表

javascript - 结合 vuejs v-repeat 和 php foreach 循环?

php - 上传excel文件Laravel

php - 使用 Symfony2 和 Doctrine 的用户的独立数据库

php - 如何替换多维数组中的值 - PHP

mysql - 从多个表创建 UNIQUE View ,其中某些字段被忽略

php - Sublimetext php-cs-fixer 将命名空间更改为小写