Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

you may want to read on model observers http://laravel.com/docs/4.2/eloquent#model-observers

Last updated 2 years ago.
0

Thanks alainbelez, the observers offer the opportunity to change the model data but do they allow me to change the SQL?

I need to be able to do 'UPDATE blah SET a=1, b=2, dataVersion = dataVersion + 1 WHERE blah blah AND dataVersion = 1'

The bold bit needs to be done at the database level, in order to ensure accuracy. If I increment this value in the model, it would not do what it needs to do. It needs to be changed in a serialised way.

Last updated 2 years ago.
0

The Query Builder method increment() does it at the database level rather than just increment the models value and saves the data.

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Query/Builder.php#L1877

Last updated 2 years ago.
0

In order to build something like that there are a lot of ways.

The simpler one which comes to my mind is this:

  1. Use timestamps() on Eloquent models
  2. Add a form input 'updated_at' so that the form sends to the controller the last updated_at date of the model you want to update
  3. When updating the model, check if current updated_at is equal to the submitted updated_at. If not, the model was meanwhile updated by another user and the operation is stopped
Last updated 2 years ago.
0

micheleangioni said:

In order to build something like that there are a lot of ways.

The simpler one which comes to my mind is this:

  1. Use timestamps() on Eloquent models
  2. Add a form input 'updated_at' so that the form sends to the controller the last updated_at date of the model you want to update
  3. When updating the model, check if current updated_at is equal to the submitted updated_at. If not, the model was meanwhile updated by another user and the operation is stopped

Hi, Thanks for offering that suggestion. Unless I misunderstood it, the check is done at the controller/model level. Alas, I need it to be done at the very last possible moment, which would be when the db engine (MySQL in my case) is about to write the record, as it removes the possibility that someone else can sneak in and have his record written.

For example, 1- I read record 2- make some changes 3- model checks for matching timestamps (ie reads old record and checks against new values)

----- another user saves the record

4- I go ahead and save the record, obliterating the other guy's changes :-(

The problem is that step 3 does not guarantee a lock on the record whereas a WHERE clause in the UPDATE does.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.