php - Laravel:如何验证 DB::transaction 函数是否正常工作?

标签 php laravel-5

我在我的 Controller 中使用了 DB::transaction 函数,

public function store(){        
    $plant = new Plant;

    DB::transaction(function()
    {
        Plant::create(request(['name','plant_code','place']));    
    });    
}

我想知道我使用该功能的方式是否正常,我需要验证它是否正常工作?

最佳答案

作为 documentation说明你有两个选择:

  1. Closure 的自动交易:

You may use the transaction method on the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction Closure, the transaction will automatically be rolled back. If the Closure executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction method

DB::transaction(function () {
    // Interacting with the database
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);
});
  1. 手动使用事务:

如果您想手动开始事务并完全控制回滚和提交,您可以在 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/

相关文章:

php - 如何只刷新用户点击过的div

laravel - 如何从不是 Controller 方法的方法发送响应?

php - 具有一对多关系的多个表(Laravel)

php - 如何在 php docker 容器上安装/启用 pdo-odbc 驱动程序?

php - 多表SQL搜索查询

php - set_error_handler() 不适用于 fatal error

php - 使用 Firebase 和 PHP 在 iOS 中推送通知

php - 更新 Laravel 中的关系

javascript - 使用 Vue 和 Axios 进行投票按钮

Laravel 5.2 App\Http\Controllers\Auth\AuthController@register 不存在