如何使用Symfony原理从数据库中克隆所有数据?

时间:2019-04-08 12:06:42

标签: php symfony doctrine entity clone

我尝试克隆data实体中具有itemcf7c1ae00f的所有记录

    $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();

在我的数据库中,有5条记录。因此,我希望再添加5条记录。但是只添加一个记录。

1 个答案:

答案 0 :(得分:1)

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();