Monday, 7 October 2013

CakePHP locking tables

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();
            sprintf('LOCK TABLES %s AS %s WRITE;',
        $recordsThisYear = $model->find(
                '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 :