1

I have a one-to-many self-referecing relation and I want to clone the entity like follows:

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

In doctrine I represented the relation as follows:

 /**
 * @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;

and the clone function:

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

and the method that calls it:

    public function clone(Product $product){

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

    $clonedProduct = clone $product;

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

    return $clonedProduct;
}

but gives 500 error saying that it is returned entity of type /Product and integer is received. How to solve this?

IleNea
  • 569
  • 4
  • 17

1 Answers1

0

Answer like this

Entity

/**
 * @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;
        }
    }
}

Method

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

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

    return $clonedProduct;
}
thm
  • 1
  • 1