I'm trying to clone an entity, having a one-to-many self-referencing in the class and the goal is to display as follows:
parent entity:
product {
id: 34
parent_product_id: null
clone_products_id: [12,45,24]
}
child clone entity:
product {
id: null
parent_product_id: 34
clone_products_id: null
}
I succeed cloning the entity, but in the parent the value of array clone_products_id is always null, and can't figure out why. My entity code:
/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="parentProduct", cascade={"persist"})
*/
private $clonedProduct;
/**
* @ORM\ManyToOne(targetEntity="Product", inversedBy="clonedProduct", cascade={"persist"})
* @ORM\JoinColumn(name="parent_product_id",referencedColumnName="id")
*/
private $parentProduct;
public function __construct(){
$this->clonedProduct = new \ArrayCollection();
}
//getting the ids of the clones
/*
* @Groups({"product"})
*/
public function getClonedProductIds(){
$clones = $this->getClonedProduct();
$idsClone = new \ArrayCollection();
foreach ($clones as $item) {
$id = $item->getId();
$idsClone->add($id);
}
return $idsClone;
}
and the clone function:
public function clone(Product $product){
$em = $this->container->get('doctrine.orm.entity_manager');
$clonedProduct = clone $product;
$clonedProduct->setParentProduct($product);
$em->persist($clonedProduct);
$em->flush();
return $clonedProduct;
}
and the main function that calls our clone function:
public function productAction(){
$clonedProduct = $productRepo()->clone($product);
return $this->json($clonedProduct, Response::HTTP_OK, [],
['groups' => ['product']]);
}
So the only problem is that the ids of the clones aren't in the clonedProduct array. Any idea how to resolve it?
I resolved the issue, I created the method:
public function addToArray($product)
{
this->clonedProduct[] = $product;
return $this;
}