Laravel:做一个查询更新然后,如果成功,则执行下一个,否则,不执行任何操作

问题描述 投票:0回答:1

所以,我想更新两个具有相同值的不同用户帐户。

场景:用户1向用户2转账:

$transfer_from = $account->decrement('balance', $amount);

$transfer_to = Account::where('user_wallet_address', $receiver_wallet_address)->increment('balance', $amount);

但是,我想要的是这样的:

$account->decrement('balance', $amount)->$transfer_to;

if the decrement succeeds, then update the other user's balance, otherwise, both should fail一样

思考?

laravel-5 laravel-5.2 laravel-5.1
1个回答
0
投票

请使用数据库事务功能

见下面的代码示例:

public function readRecord() {
    DB::beginTransaction();
    try {
        // put your code here in try block

         $transfer_from = $account->decrement('balance', $amount);
         $transfer_to = Account::where('user_wallet_address', $receiver_wallet_address)->increment('balance', $amount); 
        DB::commit();
    } catch (Exception $ex) {
        // If any failure case generate, it will rollback the DB operations automatically.
        DB::rollBack();
        echo $ex->getMessage() . $ex->getLine();
    }

我希望这能帮到您。在这种情况下,如果生成任何故障情况,它将自动恢复数据库转移,您无需执行任何操作。

参考网址:https://laravel.com/docs/5.7/database

© www.soinside.com 2019 - 2024. All rights reserved.