有没有办法在symfony2中使用实体管理器(doctrine)手动指定事务,或者可能是在单个事务中完成的自然方式,我在下面做两个事情?
// creating screen object...
//Creating user object...
//flush the screen into database in order to get the Id to relate the server (user) to
$em->persist($screen);
$em->flush();
//Get id of just inserted screen and attach that to new server (user)
$tempRecordId = $screen->getId();
$tempEntity = $em->getRepository('BizTVContainerManagementBundle:Container')->find($tempRecordId);
$entity->setScreen($tempEntity);
//Flush the user also into database
$em->persist($entity);
$em->flush();
请参阅我必须刷新我的第一个实体以获取它的ID,所以我可以将我的第二个实体与我的第一个实体联系起来......
答案 0 :(得分:23)
try {
$em->getConnection()->beginTransaction();
// do your thing here
$em->getConnection()->commit();
} catch (\Exception $e) {
$em->getConnection()->rollback();
throw $e;
}
答案 1 :(得分:7)
你为什么不这样做:
// creating screen object...
//Creating user object...
$entity->setScreen($screen);
$em->persist($screen);
$em->persist($entity);
$em->flush();