データベース取引


この素晴らしい記事https://fideloper.com/laravel-database すべての値を確信することができるように、1つ以上のテーブルに複数のデータを入力したり変更したりするときに、トランザクションに関する取引とその重要性について話し合うトランザクション​​テーブルに正しく入力されているので、次のプロジェクトであなたに役立つことを願っています.
  • 取引なしで
  • // Create Account
    $newAcct = Account::create([
        'accountname' => Input::get('accountname'),
    ]);
    
    // Create User
    $newUser = User::create([
        'username' => Input::get('username'),
        'account_id' => $newAcct->id,
    ]);
    
  • トランザクションツールセット
  • // Start transaction
    beginTransaction();
    
    // Run Queries
    $acct = createAccount();
    $user = createUser();
    
    // If there's an error
    //    or queries don't do their job,
    //    rollback!
    if( !$acct || !$user )
    {
        rollbackTransaction();
    } else {
        // Else commit the queries
        commitTransaction();
    }
    
  • 基本取引
  • DB::transaction(function()
    {
        $newAcct = Account::create([
            'accountname' => Input::get('accountname')
        ]);
    
        $newUser = User::create([
            'username' => Input::get('username'),
            'account_id' => $newAcct->id,
        ]);
    
        if( !$newUser )
        {
            throw new \Exception('User not created for account');
        }
    });
    
  • 高度取引
  • // Start transaction!
    DB::beginTransaction();
    
    try {
        // Validate, then create if valid
        $newAcct = Account::create( ['accountname' => Input::get('accountname')] );
    } catch(ValidationException $e)
    {
        // Rollback and then redirect
        // back to form with errors
        DB::rollback();
        return Redirect::to('/form')
            ->withErrors( $e->getErrors() )
            ->withInput();
    } catch(\Exception $e)
    {
        DB::rollback();
        throw $e;
    }
    
    try {
        // Validate, then create if valid
        $newUser = User::create([
            'username' => Input::get('username'),
            'account_id' => $newAcct->id
        ]);
    } catch(ValidationException $e)
    {
        // Rollback and then redirect
        // back to form with errors
        DB::rollback();
        return Redirect::to('/form')
            ->withErrors( $e->getErrors() )
            ->withInput();
    } catch(\Exception $e)
    {
        DB::rollback();
        throw $e;
    }
    
    // If we reach here, then
    // data is valid and working.
    // Commit the queries!
    DB::commit();
    

    私はいくつかの基本的なポイントを提示しようとしたが、深く行くには、ソースを参照してください.
    私はあなたが私と一緒に楽しんで、私はすべてのすべてを検索するあなたを崇拝してほしい.