php - Doctrine2 - 一次多次插入

标签 php mysql symfony doctrine-orm

我是 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/

相关文章:

php - 在 Windows 中使用 PHP 创建受密码保护的 Zip 文件

php - 导入 LOAD DATA INFILE 时将我的 php 变量连接到 csv 数据

javascript - 当使用 ajax 从其他页面加载内容时,Angularjs 代码不起作用

php - 如何使用带有时间戳的 mysql "LIKE"语法?

mysql - 如何获取单行中多列的最大值?

symfony - symfony 2.0 有多稳定或不稳定?

php - 在 Symfony2 中克隆另一个域的 session cookie

mysql - phpMyAdmin,有什么东西可以添加到 sql 来关闭该查询的缓存吗?

mysql - 数组关联和数据库设计

php - 在表单验证之前设置实体参数