我在User.php和Timesheet.php之间有一个OneToOne关系。
在这里你可以看到我的代码:
$toDelete =
$this->getDoctrine()->getRepository('VitamedicsProjectBundle:Timesheet')
->findOneBy(array('name' => 'timesheet', 'user' => $this->getUser()));
if($toDelete){
$this->_em()->remove($toDelete);
$this->_em()->flush();
}
$timesheet->setUser($this->getUser());
$timesheet->setName('timesheet');
$this->_em()->persist($timesheet);
$this->_em()->flush();
因此,如果用户已经链接到时间表,我需要删除时间表,然后才能添加其他时间表。
当我尝试这段代码时,如果我已经有一张时间表,我测试时会删除数据库中的行,但我总是有错误Duplicate entry....
我想如果我在坚持之前移除并冲洗并冲洗另一个它会有效..
答案 0 :(得分:0)
好吧,可能你有User
实体作为拥有方。刷新时,仍然在用户对象中设置了时间表对象,因此管理器不会将其删除(或立即删除并创建新的对象)。
因此,您需要做的是取消时间表与用户对象的链接:
if($toDelete){
$this->getUser()->setTimesheet(null);
$this->_em()->remove($toDelete);
$this->_em()->flush();
}