Doctrine2 ORM 选择更新

2022-01-16 00:00:00 concurrency php mysql doctrine

您能否建议一种如何使用 Doctrine 实现 SELECT FOR UPDATE 的方法?

Could you suggest an approach how to implement SELECT FOR UPDATE with Doctrine?

我需要读取一个计数器值,然后在 PHP 代码中使用它,并在其他人(来自另一个进程)使用相同的值之前立即递增该值.

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

推荐答案

锁定支持

Doctrine 2 实现 对实体的锁定支持:

<?php
use DoctrineDBALLockMode;
use DoctrineORMOptimisticLockException;

$theEntityId = 1;
$expectedVersion = 184;

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

    // do the work

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

本机 sql

另外,你可以抛出执行原始 SQL:

Native sql

Also, you can do it throws execute raw SQL:

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

然后

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

相关文章