所以,我想更新两个具有相同值的不同用户帐户。
场景:用户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
一样
思考?
请使用数据库事务功能
见下面的代码示例:
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();
}
我希望这能帮到您。在这种情况下,如果生成任何故障情况,它将自动恢复数据库转移,您无需执行任何操作。