我在我的 Controller 中使用了 DB::transaction
函数,
public function store(){
$plant = new Plant;
DB::transaction(function()
{
Plant::create(request(['name','plant_code','place']));
});
}
我想知道我使用该功能的方式是否正常,我需要验证它是否正常工作?
最佳答案
作为 documentation说明你有两个选择:
- 带
Closure
的自动交易:
You may use the
transaction
method on theDB
facade to run a set of operations within a database transaction. If an exception is thrown within the transactionClosure
, the transaction will automatically be rolled back. If theClosure
executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using thetransaction
method
DB::transaction(function () {
// Interacting with the database
DB::insert(...);
DB::insert(...);
DB::insert(...);
});
- 手动使用事务:
如果您想手动开始事务并完全控制回滚和提交,您可以在 DB facade 上使用 beginTransaction 方法:
DB::beginTransaction();
可以通过rollBack方法回滚事务:
DB::rollBack();
最后,您可以通过 commit 方法提交事务:
DB::commit();
手动使用交易链接到 try catch
block ,如下所示:
DB::beginTransaction();
try {
// Interacting with the database
DB::insert(...);
DB::insert(...);
DB::insert(...);
DB::commit(); // Commiting ==> There is no problem whatsoever
} catch (\Exception $e) {
DB::rollback(); // rollbacking ==> Something went wrong
}
为了测试交易,您可以在不抛出任何异常的情况下运行您的示例 ==> 预期结果:一切正常,Plant 将被创建。
如果你抛出一个异常,事务将被回滚并且 Plant 将不会在数据库中创建:
public function store(){
$plant = new Plant;
DB::transaction(function()
{
Plant::create(request(['name','plant_code','place']));
throw new ModelNotFoundException("Just for testing :)");
});
}
在 Controller 顶部添加 use Illuminate\Database\Eloquent\ModelNotFoundException;
;)
关于php - Laravel:如何验证 DB::transaction 函数是否正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46884541/