Laravel:执行一个查询更新,然后,如果成功,则执行下一个,否则,两者都不执行
Laravel: Do one query update and then, if that succeeds, do the next, otherwise, do neither
所以,我想用相同的值更新两个不同的用户帐户。
场景:用户 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();
}
希望对您有所帮助。在这种情况下,如果生成任何失败案例,它将自动恢复数据库易位,您无需执行任何操作。
所以,我想用相同的值更新两个不同的用户帐户。
场景:用户 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();
}
希望对您有所帮助。在这种情况下,如果生成任何失败案例,它将自动恢复数据库易位,您无需执行任何操作。