Here are my two cents on the issue.
The code below is a function from a behaviour that tries to create an additional unique key on
a field named code, by counting the number of records created this year. The important part
in the locking procedure is that we must specify the AS
clause in the LOCK TABLES
statement or otherwise the $model->find()
function will not work complaining that the table is locked.
public function getNextCode(&$model) { $thisYear = date('Y'); $dbo = $model->getDataSource(); $dbo->execute( sprintf('LOCK TABLES %s AS %s WRITE;', $model->table, $model->alias ) ); $recordsThisYear = $model->find( 'count', array( 'recursive' => -1, 'conditions' => array( $model->alias .'.code LIKE' => $thisYear.'%' ) ) ); $dbo->execute('UNLOCK TABLES'); return sprintf('%d-%06d', $thisYear, $recordsThisYear + 1); }
The original idea for the post and function cake from a doWeb posting available through here.
No comments :
Post a Comment