10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel5.3でselect for update する方法

Last updated at Posted at 2017-01-11

select for updateしたい!

公式ドキュメントにはサラッとtransactionの事が書いていますが、select for updateはどうするのかがわかりません。

laravelのtransactionはなんて素敵な仕組み

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:

  • transactionメソッドのclosure内で書いておけば、commitやrollbackも自動でやってくれる素敵仕様
  • デッドロックした場合の再試行もtransactionメソッドの引数で指定できます。

結論

  • いやーオフィシャルドキュメントを疑ってしまうぐらい簡単に書けますね・・・。
\DB::transaction(function () use ($id) {
    $model = \Hoge\Model::lockForUpdate()->find($id);
    $model->name = 'ほげ太郎';
    $model->save();
});
10
10
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
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?