【问题标题】:Symfony: clone object with Datetime field and add days to cloned object datesSymfony:使用 Datetime 字段克隆对象并在克隆对象日期中添加天数
【发布时间】:2017-11-14 17:16:56
【问题描述】:

我有一个看似简单的问题,但经过几个小时的尝试和错误后,我只得到错误的结果。

目标是复制一个对象ConventionHallReservation 具有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 方法的服务中手动创建新实体:/

标签: symfony datetime clone


【解决方案1】:

当您克隆Convention 对象时,您不会将hallReservation 属性设置为新的Collection。 Doctrine 中的OneToMany 关系映射到Collection 对象,因此当您克隆Convention 对象时,您会在克隆的对象中获得对原始hallReservation 集合的引用。

你可以试试这样的:

<?php

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @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');
        $reservations = new ArrayCollection();

        foreach ($this->hallReservation as $hallR)
        {
            $clonedR = clone $hallR;
            $clonedR->setConvention($this);
            $newRDate = clone $hallR->getDate();
            $clonedR->setDate($newRDate);
            $reservations->add($clonedR);
        }

        $this->hallReservation = $reservations;
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-07
    • 2018-03-21
    • 2011-05-15
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2013-01-03
    • 2017-02-11
    • 2011-07-10
    相关资源
    最近更新 更多