LoginSignup
10
8

More than 5 years have passed since last update.

LaravelでSQLServerのトランザクション管理

Posted at

背景

LaravelではDB操作にPDOを利用しているが、
PDOのトランザクションメソッド(beginTransaction等)がSQLServerに対応していないので、
Laravel標準の

DB::transaction(function()
{
    ...
});

や、

DB::beginTransaction();

ではSQLServerのトランザクション管理ができない。

解決策

トランザクション処理のSQLを直接実行する。

サンプルコード

use DB;
use Exception;

try {
    DB::connection('sqlsrv')->statement('BEGIN TRANSACTION');

    ...

    DB::connection('sqlsrv')->statement('COMMIT TRANSACTION');
} catch (Exception $e) {
    DB::connection('sqlsrv')->statement('ROLLBACK TRANSACTION');
}

参考

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8