克隆不适用于学说symfony

时间:2017-10-04 10:11:29

标签: symfony doctrine one-to-many

我有一对多的自我引用关系,我想克隆实体,如下所示:

 product{
   cloned_product : [23,32,32]
   parent_product_id: 12
 }

在学说中,我将关系表示如下:

 /**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Product", mappedBy="parentProductId")
 */
private $clonedProduct;

/**
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Product", inversedBy="clonedProduct", cascade={"persist"})
 * @JoinColumn(name="parent_product_id", referencedColumnName="id")
 */
private $parentProductId;

和克隆功能:

public function __clone()
{
    $this->setParentProductId($this->id);
    if ($this->id){
        $this->id =null;
    }
}

以及调用它的方法:

    public function clone(Product $product){

    $em = $this->container->get('doctrine.orm.entity_manager');

    $clonedProduct = clone $product;

    $em->persist($clonedProduct);
    $em->flush();

    return $clonedProduct;
}

但是给出500错误,说它是类型/ Product的返回实体并且接收到整数。怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

Answer like this

<强>实体

/**
 * @OneToMany(targetEntity="Product", mappedBy="parent", cascade={"persist"})
 */
private $children;

/**
 * @ManyToOne(targetEntity="Product", inversedBy="children", cascade={"persist"})
 * @JoinColumn(name="parent_id", referencedColumnName="id")
 */
private $parent;

public function __clone()
{
    if (null !== $this->id) {
        $this->setId(null);
        if (null !== $this->children) {
            $childrenClone = new ArrayCollection();
            /** @var Product $item */
            foreach ($this->children as $item) {
                $itemClone = clone $item;
                $itemClone->setParent($this);
                $childrenClone->add($itemClone);
            }
            $this->children = $childrenClone;
        }
    }
}

方式

public function clone(Product $product)
{
    $em = $this->getContainer()->get('doctrine.orm.default_entity_manager');

    $clonedProduct = clone $product;
    $em->persist($clonedProduct);
    $em->flush();

    return $clonedProduct;
}