【发布时间】:2017-08-03 10:36:04
【问题描述】:
我的应用程序使用 Doctrine2 EntityManager。在一个循环中,我喜欢将 5 个数据集插入到不同的表中。
public function insertRate($dateObj, $rate)
{
$model = new TestModel();
$model
->setDate($dateObj)
->setRate($rate);
$this->getEntityManager()->persist($model);
try {
$this->getEntityManager()->flush();
} catch (\Exception $e) {
$currentTime = new \DateTime();
echo 'Duplicate entry <br>' .
'At Time ' . $currentTime->format('Y-m-d H:i') . "<hr>";
}
}
如果可能由于重复条目(唯一约束)而导致插入 2 失败,则 entityManger 将不会执行以下 3 条语句,因为管理器已关闭。
我使用这样的解决方法:
$currentEm = $this->em;
if (!$currentEm->isOpen()) {
$this->em = $currentEm->create(
$currentEm->getConnection(), $currentEm->getConfiguration());
}
使用此解决方法,将设置一个新的 entityManger,但 auto_increment id 不像 1、2、3... 而是 1、5、10、15...
我不想检查是否会因为额外的选择而违反唯一约束。
我该如何解决这个问题,这个解决方法可以吗?
【问题讨论】:
-
你能告诉我们插入数据的代码吗?
-
无论如何,依赖异常最终都会咬你一口。进行查询并完成它。
-
失败插入时自动增量的差距是由数据库引擎的设计决定的。这里是many questions about it。
标签: php doctrine-orm