我是 Doctrine 的新手,对我来说还有一些模糊的地方。在这种情况下,我使用循环和实体管理器在数据库中插入新记录。它工作正常,但我注意到 Doctrine 按实体进行插入查询,这可能会变得非常庞大。
使用 Doctrine2 和 Symfony 2.3,我想知道我们如何设置它,这样它就只需要 1 个包含所有值的插入查询(我们当然只讨论 1 个实体)。
我的意思是改变这个:
INSERT INTO dummy_table VALUES (x1, y1)
INSERT INTO dummy_table VALUES (x2, y2)
进入
INSERT INTO dummy_table VALUES (x1, y1), (x2, y2)
这是我的代码:
$em = $this->container->get('doctrine')->getManager();
foreach($items as $item){
$newItem = new Product($item['datas']);
$em->persist($newItem);
}
$em->flush();
最佳答案
根据this answer , Doctrine2 不允许你将多个 INSERT 语句合并为一个:
Some people seem to be wondering why Doctrine does not use multi-inserts (insert into (...) values (...), (...), (...), ...
First of all, this syntax is only supported on mysql and newer postgresql versions. Secondly, there is no easy way to get hold of all the generated identifiers in such a multi-insert when using AUTO_INCREMENT or SERIAL and an ORM needs the identifiers for identity management of the objects. Lastly, insert performance is rarely the bottleneck of an ORM. Normal inserts are more than fast enough for most situations and if you really want to do fast bulk inserts, then a multi-insert is not the best way anyway, i.e. Postgres COPY or Mysql LOAD DATA INFILE are several orders of magnitude faster.
These are the reasons why it is not worth the effort to implement an abstraction that performs multi-inserts on mysql and postgresql in an ORM.
您可以在此处阅读有关 Doctrine2 批处理的更多信息: https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/batch-processing.html
您可以切换到 DBAL 或通过在一定数量的插入后刷新实体管理器来小批量处理数据:
$batchSize = 20;
foreach ($items as $i => $item) {
$product = new Product($item['datas']);
$em->persist($product);
// flush everything to the database every 20 inserts
if (($i % $batchSize) == 0) {
$em->flush();
$em->clear();
}
}
// flush the remaining objects
$em->flush();
$em->clear();
关于php - Doctrine2 - 一次多次插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18654530/