首页 > 解决方案 > Laravel BD::rollBack 不要在我的代码中工作

问题描述

我编写了下面的代码以验证余额和历史记录将保存在数据库中或不保存的交易。但是,当我运行代码并检查数据库时,我发现余额仍在被插入银行而不是被取消。可能是什么错误?

下面是我的余额模型负责操作的方法代码

public function deposit(float $value) : Array {

        DB::beginTransaction();

        $totalBefore = null;
        // $totalBefore = $this->amount ? $this->amount : 0;
        $this->amount += number_format($value, 2, ".", '');
        $deposit = $this->save();

        $historic = auth()->user()->historics()->create([
            'type'          => 'I', 
            'amount'        => $value, 
            'total_before'  => $totalBefore, 
            'total_after'   => $this->amount, 
            'date'          => date('Ymd'),
        ]);

        if ($deposit && $historic) {
            DB::commit();

            return [
                'success' => true,
                'message' => 'Sucesso ao recarregar!'
            ];
        }

        else {
            DB::rollBack();

            return [
                'success' => false,
                'message' => 'Falha ao recarregar!'
            ];
        }     
    } 

标签: databaselaravel

解决方案


当您使用 save() 时,它不会被 db::rollBack() 回滚。


推荐阅读