Kuba Petržílka Kuba Petržílka - 10 months ago 110
MySQL Question

Doctrine2 ORM select for update

Please could you suggest me some approach how to implement

with Doctrine?

I need to read some counter value, use it in PHP code and immediately increment the value before someone else (from another process) uses the same value.


Locking support

Doctrine 2 implements Locking support for entities:

use Doctrine\DBAL\LockMode;
use Doctrine\ORM\OptimisticLockException;

$theEntityId = 1;
$expectedVersion = 184;

try {
    $entity = $em->find('User', $theEntityId, LockMode::OPTIMISTIC, $expectedVersion);

    // do the work

} catch(OptimisticLockException $e) {
    echo "Someone else has already changed this entity. Apply the changes again!";

Native sql

Also, you can do it throws execute raw SQL:

$em->getConnection()->exec('LOCK TABLES table_name WRITE;'); //lock for write access

and then

$em->getConnection()->exec('UNLOCK TABLES;');