Laravel lockforupdate (Pessimistic Locking)

后端 未结 2 2084
孤独总比滥情好
孤独总比滥情好 2020-12-14 22:59

i\'m trying to figure out how to use/test the lockforupdate correctly, but i found is not function like what i expected

this is just testing

public f         


        
相关标签:
2条回答
  • 2020-12-14 23:19

    Read This Article Reference

    Pessimistic vs Optimistic Locking in Laravel

    • SharedLock:

      DB::table('users')->where('votes', '>', 100)->sharedLock()->get();
      
    • LockForUpdate:

      DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
      

    Laravel Docs

    0 讨论(0)
  • 2020-12-14 23:21

    This work, finally, but still don't understand what sharedLock(LOCK IN SHARE MODE) and lockForUpdate(FOR UPDATE) different

        public function index() {
            return dd(\DB::transaction(function() {
                if (\Auth::guard('user')->check()) {
                    $model = \App\Models\User::lockForUpdate()->find(1);
                    sleep(30);
                    $model->point = 100000;
                    $model->save();
                } else {
                    $model = \App\Models\User::lockForUpdate()->find(1);
                    $model->point = $model->point + 1;
                    $model->save();
                }
    
                return $model;
            }));
        }
    
    0 讨论(0)
提交回复
热议问题