我用的是Symfony 3.4和Doctrine。我需要使用原则更新大量实体(300k+)。我读过批处理文章form Doctrine文档,也读过堆栈中的主题,但问题是,尽管批处理的大小(20、100、200、500),但当我接近20k处理实体时,我还是会出现“内存不足”错误。
这是我的功能。
有人,请给我一个提示/建议,如何避免这种情况?
protected function execute(InputInterface $input, OutputInterface $output): void
{
$io = new SymfonyStyle($input, $output);
$em = $this->getContainer()->get('doctrine.orm.entity_manager');
$em->getConfiguration()->setSQLLogger(null);
$repository = $em->getRepository('AppBundle:Order');
$qb = $repository->createQueryBuilder('o');
$totalCount = (int) $qb->select($qb->expr()->count('o'))
->where($qb->expr()->eq('o.amountOut', 0))
->getQuery()
->getSingleScalarResult();
$progressBar = $io->createProgressBar($totalCount);
$query = $qb->select('o')
->where($qb->expr()->eq('o.amountOut', 0))
->getQuery();
$iterableResult = $query->iterate();
$batchSize = 100;
$i = 0;
foreach ($iterableResult as $row) {
/** @var Order $order */
$order = $row[0];
$commissionsArr = $this->calcCommissionInOutFromOrder($order);
$amountOut = $order->getTransferAmount();
$order->setAmountOut($amountOut);
$order->setCommissionIn($commissionsArr['commission_in']);
$order->setCommissionOut($commissionsArr['commission_out']);
$em->persist($order);
$progressBar->advance();
if (0 === ($i % $batchSize)) {
$em->flush();
$em->clear();
}
++$i;
}
$em->flush();
$io->success('Suckess');
}发布于 2018-09-10 08:57:31
在Memory leak when executing Doctrine query in loop中找到了实际答案。
引用:“我通过在命令中添加--不调试的来解决这个问题。结果发现,在调试模式下,分析器在内存中存储每个查询的信息。”
它真的起作用了。使用memory_get_usage(),我检查了它。
https://stackoverflow.com/questions/52225392
复制相似问题