【发布时间】:2025-12-25 22:55:07
【问题描述】:
我有一个看起来像这样的函数:
function findByAndCreateIfNotExists($criteria){
$entity = $this->findBy(['criteria'=>$criteria]);
// this is the problem area, if request 1 is still creating the entity, request 2 won't find it yet.
if (! $entity) {
$entity = $this->createEntity($criteria);
}
return $entity;
}
这个函数被各种请求使用,我发现并发请求有时会尝试创建同一个实体,抛出一个DBALException抱怨唯一键的重复条目。
我考虑过LOCK TABLES,如下所述:
How to lock a whole table in symfony2 with doctrine2?
但鉴于 Doctrine 中没有执行此操作的功能,我猜这不是首选方法。我的问题是,如何防止并发请求尝试创建相同的实体并始终返回正确的实体?
【问题讨论】:
标签: php mysql symfony doctrine-orm