use*_*101 4 php mysql symfony doctrine-orm
我想通过批处理将 10 000 行插入到数据库中。第一步,我需要从数据库中选择一些对象,然后对这些对象进行交互,并为每个对象将另一个对象持久化到数据库中。这是代码示例:
$em = $this->getDoctrine()->getManager();
$products = $em->getRepository('MyBundle:Product')->findAll(); // return 10 000 products
$category = $em->getRepository('MyBundle:Category')->find(1);
$batchsize = 100;
foreach ($products as $i => $product) {
$entity = new TestEntity();
$entity->setCategory($category);
$entity->setProduct($product); // MyEntity And Product is OneToOne Mapping with foreign key in MyEntity
$em->persist($entity);
if ($i % $batchsize === 0) {
$em->flush();
$em->clear();
}
}
$em->flush();
$em->clear();
Run Code Online (Sandbox Code Playgroud)
它返回此错误:
A new entity was found through the relationship 'Handel\GeneratorBundle\Entity\GenAdgroup#product' that was not configured to cascade persist operations for entity
Run Code Online (Sandbox Code Playgroud)
我认为问题在于clear(),删除内存中的所有对象,包括 $products和 $ category。
如果我cascade={"persist"}在关联中使用,则学说会在 db 中插入新的类别行。
经过一些尝试,我犯了一些肮脏的实体错误。
我做错了什么吗?这项工作的解决方案和最佳实践是什么?非常感谢回答
解决方案只是清除那些正在更改/创建的对象。那些不变的应该留在 EntityManager 中。
像这样
$em->clear(TestEntity::class);
$em->clear(...);
Run Code Online (Sandbox Code Playgroud)
如果您在没有参数的情况下清除它,它将分离实体管理器下当前的所有对象。这意味着如果您尝试重用它们,它将在您获得时抛出错误。例如,唯一的文件将被复制并引发该错误。