Hello,
I'm doing an intervention on my application regarding the way to generate a unique and sequential Order Number.
At the moment the Order Number is generated on beforeValidationOnCreate()
, where a query is performed on the table looking for the latest record and setting as order number the same retreived value + 1
.
I've changed this behaviour because concurrent transactions sometimes cause two records being created with the same order number (the "second" order causes database exception for unique index violation, that is a correct behaviour). On the other hand, using forUpdate()
or sharedLock()
during the order creation transaction to retreive the latest order number causes this error: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction
.
So, I've decided to do this:
OrderNumber
field becomesDEFAULT NULL
with aUNIQUE
index- On
afterCreate()
, I copy the value ofOrderId
intoOrderNumber
and save the model:$this->save()
The problem is that if I perform a $order->refresh()
at some point after it was created/saved this way (and I do the refresh()
on the same instance of the created model), I get this error:
Phalcon\Mvc\Model\Exception
The record cannot be refreshed because it does not exist or is deleted
File: phalcon/mvc/model.zep
Line: 3433
$order
dirty state is PERSISTENT
when this happens.
I'm sure the problem is that I save()
a model on afterCreate()
, causing the model to be no more a "creation" and making it become an "update".
How can I fix this problem?
Thank you very much
Using PHP 7.0 with Phalcon 3.2.0 on Debian 8 with MySql 5.7