Laravel事务:如何提交一些查询而不是全部回滚?
Laravel Transaction: How to do commit some queries instead of rollback all?
异常中止请求的事务块,以便回滚。但是现在每当出现异常时,都需要存储数据——异常的详细信息到table。中止请求时,insert/update 查询也会回滚。
\DB::transaction(function () use ($request) {
try{
// operations
}catch(Exception $e){
$exception_model = new ExceptionModel();
$exception_model->user = $request->user_info;
$exception_model->detail = $e;
$exception_model->save();
abort(Response::HTTP_BAD_REQUEST, 'Something went wrong');
}
});
但由于它会自动回滚(即,laravel 事务关闭),异常模型更改也会回滚。怎么做到的?
您可以在闭包之外手动使用事务。这样您就可以将数据存储在 $exception_model
:
try{
DB::beginTransaction(); //Initiate transaction
// operations
DB::commit(); //Commit transaction after all the operations
}catch(Exception $e){
DB::rollBack(); //Rollback if the exception occurs, but still save data in your exception model
$exception_model = new ExceptionModel();
$exception_model->user = $request->user_info;
$exception_model->detail = $e;
$exception_model->save();
abort(Response::HTTP_BAD_REQUEST, 'Something went wrong');
}
在官方 documentation 部分阅读更多内容 手动使用交易
将事务放在 try 块中应该可行:
use Exception;
try {
\DB::transaction(function () use ($request) {
// operations
});
} catch (Exception $e) {
$exception_model = new ExceptionModel();
$exception_model->user = $request->user_info;
$exception_model->detail = $e;
$exception_model->save();
abort(Response::HTTP_BAD_REQUEST, 'Something went wrong');
}
异常中止请求的事务块,以便回滚。但是现在每当出现异常时,都需要存储数据——异常的详细信息到table。中止请求时,insert/update 查询也会回滚。
\DB::transaction(function () use ($request) {
try{
// operations
}catch(Exception $e){
$exception_model = new ExceptionModel();
$exception_model->user = $request->user_info;
$exception_model->detail = $e;
$exception_model->save();
abort(Response::HTTP_BAD_REQUEST, 'Something went wrong');
}
});
但由于它会自动回滚(即,laravel 事务关闭),异常模型更改也会回滚。怎么做到的?
您可以在闭包之外手动使用事务。这样您就可以将数据存储在 $exception_model
:
try{
DB::beginTransaction(); //Initiate transaction
// operations
DB::commit(); //Commit transaction after all the operations
}catch(Exception $e){
DB::rollBack(); //Rollback if the exception occurs, but still save data in your exception model
$exception_model = new ExceptionModel();
$exception_model->user = $request->user_info;
$exception_model->detail = $e;
$exception_model->save();
abort(Response::HTTP_BAD_REQUEST, 'Something went wrong');
}
在官方 documentation 部分阅读更多内容 手动使用交易
将事务放在 try 块中应该可行:
use Exception;
try {
\DB::transaction(function () use ($request) {
// operations
});
} catch (Exception $e) {
$exception_model = new ExceptionModel();
$exception_model->user = $request->user_info;
$exception_model->detail = $e;
$exception_model->save();
abort(Response::HTTP_BAD_REQUEST, 'Something went wrong');
}