【发布时间】:2015-11-07 20:37:47
【问题描述】:
我想通过批处理向数据库插入 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();
它返回此错误:
A new entity was found through the relationship 'Handel\GeneratorBundle\Entity\GenAdgroup#product' that was not configured to cascade persist operations for entity
我认为问题出在clear(),它删除了内存中的所有对象,包括 $products 和 $category。
如果我在关联中使用cascade={"persist"},则学说在数据库中插入新的类别行。
经过一些尝试,我犯了一些肮脏的实体错误。
我是不是做错了什么?这项工作的解决方案和最佳实践是什么? 非常感谢回答
【问题讨论】:
标签: php mysql symfony doctrine-orm