Search code examples
phpsymfonydoctrineentityclone

How can I clone all data from my database with Symfony doctrine?


I try to clone all records in my data entity that have the item value cf7c1ae00f

    $dataEntity= new Data();
    $cloneArray = $this->em->getRepository(Data::class)->findBy(['item' => 'cf7c1ae00f']);

    foreach ($cloneArray as $cloneItem) {
      $fieldClone = clone $cloneItem;
      $dataEntity->setItem($fieldClone);
      $this->em->persist($dataEntity);
    }
    $this->em->flush();

In my database there are 5 records. So I expect that another 5 records are added. But only one record is added.


Solution

  • You are writing the same $dataEntity 5 times with different contents. You could construct that object in the loop to solve your problem but you could also persist $fieldClone directly instead and skip the $dataEntity variable completely.

    However, entities have unique ids and that will lead to errors when you try to persist a cloned entity. You would have to empty the id and other attributes that have to be unique in the collection / database.

    You can easily set some initial values on a new object when the clone keyword is used, using the __clone() method of the class that the object belongs to.

    So if you only need to empty the id, you would add a clone method to the Data class and change the loop to:

    Data class:

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

    Cloning code:

    $cloneArray = $this->em->getRepository(Data::class)->findBy(['item' => 'cf7c1ae00f']);
    
    foreach ($cloneArray as $cloneItem) {
        # Clone the object and automatically run the `__clone()` method of the class
        $fieldClone = clone $cloneItem;
        $this->em->persist($fieldClone);
    }
    $this->em->flush();