-1

my code:

DB::transaction(function () {
       $foo = Foo::whereId(1)->lockForUpdate()->with('bars')->first();
       // dump foo & bars
       // update foo's columns
       // update bars' columns
   });

and I run this code at the same time twice, first time it can update correctly, but the second time when I query the foo, foo's columns is correct, but the bars are still old(in database it's correct), why is it and how to solve it?

Cositanto
  • 682
  • 5
  • 15

1 Answers1

3

Since you are using lockForUpdate() and want to use the new data after you update, you need to re-hydrate the model using refresh()

The refresh method will re-hydrate the existing model using fresh data from the database. In addition, all of its loaded relationships will be refreshed as well:

https://laravel.com/docs/9.x/eloquent#refreshing-models

There is a great answer by NoOorZ24 @ Laravel lockforupdate (Pessimistic Locking) explaining how the lock for transaction works to further clarify.

RG Servers
  • 1,726
  • 2
  • 11
  • 27