我尝试克隆我data
实体中具有该item
值的所有记录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();
在我的数据库中,有5条记录。因此,我希望再添加5条记录。但是只添加一个记录。
您正在$dataEntity
用相同的内容编写5次相同的内容。您可以在循环中构造该对象以解决您的问题,但也可以$fieldClone
直接将其持久保存,并$dataEntity
完全跳过该变量。
但是,实体具有唯一的ID,当您尝试保留克隆的实体时,这将导致错误。您将必须清空集合/数据库中必须唯一的id和其他属性。
clone
使用关键字时,可以使用__clone()
对象所属类的方法轻松地在新对象上设置一些初始值。
因此,如果只需要清空ID,则可以向Data
该类添加一个clone方法,并将循环更改为:
资料类别:
public function __clone() {
$this->id = null;
}
克隆代码:
$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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句