gpt4 book ai didi

php - Doctrine2 - 一次多次插入

转载 作者:IT老高 更新时间:2023-10-28 23:47:37 24 4
gpt4 key购买 nike

我是 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 usemulti-inserts (insert into (...) values (...), (...), (...), ...

First of all, this syntax is only supported on mysql and newerpostgresql versions. Secondly, there is no easy way to get hold of allthe generated identifiers in such a multi-insert when usingAUTO_INCREMENT or SERIAL and an ORM needs the identifiers for identitymanagement of the objects. Lastly, insert performance is rarely thebottleneck of an ORM. Normal inserts are more than fast enough formost situations and if you really want to do fast bulk inserts, then amulti-insert is not the best way anyway, i.e. Postgres COPY or MysqlLOAD DATA INFILE are several orders of magnitude faster.

These are the reasons why it is not worth the effort to implement anabstraction that performs multi-inserts on mysql and postgresql in anORM.

您可以在此处阅读有关 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com