【发布时间】:2017-11-14 17:16:56
【问题描述】:
我有一个看似简单的问题,但经过几个小时的尝试和错误后,我只得到错误的结果。
目标是复制一个对象Convention 与HallReservation 具有OneToMany 关系,并为此保留增加一些天数。我得到的结果是,在克隆对象和原始对象中添加了天数,我希望原始对象保持不变。
这是重要的代码:
/**
* @ORM\Entity()
*/
class Convention
{
/**
* @ORM\OneToMany(targetEntity="HallReservation", mappedBy="convention", cascade={"all"})
*/
private $hallReservation;
/**
* Clone object
*
*/
public function __clone()
{
if ($this->id)
{
$this->id=null;
$this->reference = null;
$this->registrationDate = new \Datetime('now');
foreach ($this->hallReservation as $hallR)
{
$clonedR = clone $hallR;
$clonedR->setConvention($this);
$newRDate = clone $hallR->getDate();
$clonedR->setDate($newRDate);
$this->hallReservation->add($clonedR);
}
}
}
/**
* @ORM\Entity()
*/
class HallReservation
{
/**
* @var \Date
*
* @ORM\Column(name="date", type="date")
*/
private $date;
/**
* Clone object
*
*/
public function __clone()
{
if ($this->id)
{
$this->id=null;
$clonedDate = clone $this->date;
$this->date = $clonedDate;
}
控制器代码:
$jumpInterval = $originalConventionBeginDate->diff($newDate);
foreach ($newConvention->getHallReservation() as $newHallR)
{
$prevDate = clone $newHallR->getDate();
$prevDate->add($jumpInterval);
$newHallR->setDate($prevDate);
}
$em->persist($newConvention);
$em->flush();
如您所见,我在 任何地方 都克隆了 datetime 对象,但仍会添加原始会议厅预订日期。
【问题讨论】:
-
您尝试登录
if ($this->id)块吗?您可以考虑在没有__clone方法的服务中手动创建新实体:/