表里面只有id=1,status=1的一條記錄,正常邏輯就該是回歸,數(shù)據(jù)不變,但是,db事務(wù)沒啟作用,id=1的status變成0了
這是結(jié)果 {"msg":"{\"result1\":1,\"result2\":0}"}
public function test(Request $request): \support\Response
{
Db::beginTransaction();
try {
$result1 = Db::table(Admin::$table)->whereRaw('id = 1')->update(['status' => 0]);
$result2 = Db::table(Admin::$table)->whereRaw('id = 0')->update(['status' => 0]);
if ($result1 && $result2) {
Db::commit();
return json(['result1' => $result1, 'result2' => $result2]);
}
throw new BusinessException(json_encode(['result1' => $result1, 'result2' => $result2]));
} catch (BusinessException $exception ) {
Db::rollback();
return json(['msg' => $exception->getMessage()]);
}
}
ubuntu22.04 docker環(huán)境
php 8.1
webman 1.5.7
mysql 8.0
你這個邏輯看起來有bug
1、根據(jù)你的描述,數(shù)據(jù)庫只有一個id為1的記錄,那么$result2永遠是0,if ($result1 && $result2)
永遠無法進入,必然得到你現(xiàn)在的結(jié)果
2、非常重要的一點,使用事務(wù)一定要用
try {
Db::commit();
} catch (\Throwable $e) {
Db::rollback()
}
這樣的結(jié)構(gòu)來處理事務(wù),只catch BusinessException 是不對的,因為可能產(chǎn)生其他異?;駿rror就無法捕獲,導(dǎo)致后面的所有數(shù)據(jù)庫操作都有問題。