我在控制器中使用了DB::transaction
函数,代码如下:
public function store(){
$plant = new Plant;
DB::transaction(function()
{
Plant::create(request(['name','plant_code','place']));
});
}
我想知道我使用的函数是否正确,我需要验证它是否正常工作?
我在控制器中使用了DB::transaction
函数,代码如下:
public function store(){
$plant = new Plant;
DB::transaction(function()
{
Plant::create(request(['name','plant_code','place']));
});
}
您可以在
DB
外观上使用transaction
方法来运行一组操作以便在数据库中执行事务。如果事务的Closure
中抛出异常,则事务将自动回滚。如果Closure
成功执行,则事务将自动提交。 使用transaction
方法时,您无需手动回滚或提交事务
DB::transaction(function () {
// Interacting with the database
DB::insert(...);
DB::insert(...);
DB::insert(...);
});
如果您想要手动开始一个事务并且完全控制回滚和提交,可以在DB门面上使用beginTransaction方法:
DB::beginTransaction();
DB::rollBack();
DB::commit();
手动使用事务与try catch
块相连,如下所示:
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
}
为了测试事务,您可以在不抛出任何异常的情况下运行示例 ==> 预期结果:一切正常,工厂将被创建。
如果您抛出异常,则事务将回滚,并且工厂将不会在数据库中创建:
public function store(){
$plant = new Plant;
DB::transaction(function()
{
Plant::create(request(['name','plant_code','place']));
throw new ModelNotFoundException("Just for testing :)");
});
}
use Illuminate\Database\Eloquent\ModelNotFoundException;
;)DB::rollback();
的用法吗?如果在 try 中出现异常,没有它就不会提交任何内容。 - Daniyal Javani