Rahul Govind Rahul Govind - 1 year ago 87
SQL Question

How to perform update and save operations in eloquent which are dependent on the last row of a table?

I want to perform an operation similar to the following where the attributes of the object I'm creating depends on the attributes of previous object.

$last_row = Model::orderBy('id', 'desc')->first();
$new_object = new Model()
$new_object.attr1 = $last_row->id + 1
$new_object.attr2 = $last_row->id + 2

How do you perform the necessary locking in Eloquent to ensure that line 1 is executed by only one transaction at a time?

What other code do I need to add or edit to ensure that two objects do not have the same attr1 and attr2 if line 1 is performed for both objects before either one of the objects is saved.

Answer Source

Using this method your are searching for a key that is lower than the key associated on line 1. So even if another object is created before line 2, it will not be considered on your line 2 search.

$new_object = Model::create([]);

$last_row = Model::where("id","<",$new_object")->orderBy('id', 'desc')->first();  

$new_object->attr1 = $last_row->id + 1
$new_object->attr2 = $last_row->id + 2


You could also use the timestamp to search for the newest created object. If your model have timestamps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download