Symfony2,Doctrine2:命令循环在每个循环上创建新的实体


Symfony2 & Doctrine2: Command loop creates new entity on each cycle

我有一个Symfony2 CLI脚本运行,它应该每3秒更新一个时间戳。问题是:$this->em->persist($processInfo)每次执行时都会在DB中创建一个新条目。我希望它在每个循环中都是UPDATE,而不是CREATE。

$processInfo = new ....ProcessInfo();
while(true){
     $someObject = new ..();
     $this->em()->persist($someObject);
     $this->em()->clear(); // sorry forgot this line in my initial question
     $processInfo->setLastCheckOn($now); // to know if the script is still running, we set a timestamp in the db
     $this->em()->persist($processInfo);
     $this->em()->flush();

     sleep(3);
}

任何想法?

只使用一次persist。然后,您需要提交活动事务并启动新事务,以便告诉数据库保存它们并创建新事务:

$processInfo = new ....ProcessInfo();
$this->em()->persist($processInfo);
$this->em()->getConnection()->commit();
while(true){
    $processInfo->setLastCheckOn($now); // to know if the script is still running, we set a timestamp in the db
    $this->em()->flush();
    sleep(3);
}