【问题标题】:persist() and flush() inside loop - Doctrine循环内的persist()和flush() - 教义
【发布时间】:2013-04-11 12:45:27
【问题描述】:

我想知道 ff: 代码将往返数据库多少次。

foreach ($recipients as $recipient) {
    $received_email = new ReceivedEmail();
    $received_email->setRecipient($recipient);
    $received_email->setEmail($email);

    $entityManager->persist($received_email);
    $entityManager->flush(); 
}

$recipients 是一组与 ReceivedEmail 具有一对多关系的 User 对象

$email 是一个与 ReceivedEmail 具有一对多关系的对象。

如果$recipients 有五个实体,那么循环是否会生成总共五次访问数据库?还是只有一个?

以上示例是插入新 ReceivedEmail 记录的最优化方式吗?

谢谢

【问题讨论】:

    标签: php collections orm doctrine data-access-layer


    【解决方案1】:

    将为每个持久化生成一个 INSERT 语句。

    更重要的是,您可以只显示您的 SQL 语句进行调试,只需配置 Doctrine 进行日志记录: https://stackoverflow.com/a/4585421/1815881

    在你的情况下:

    $entityManager->getConfiguration()->
                    setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
    

    对于许多插入,您应该考虑批处理:

    希望我已经揭示了问题。

    【讨论】:

    • 谢谢。我想我会在我的示例中使用 nativeSQL 插入多个 ReceivedEmail 以尽量减少数据库访问次数
    • @Athlan,您没有具体说明 flush 的作用。
    • 每个persist 的insert 语句并不意味着它会为每个persist 创建一条新记录。它将检查persisted 的对象是否已经存在,这意味着您必须为每个persist 创建一个新对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多