【问题标题】:How can I get the all Ids after persiting with doctrine using batch procces?使用批处理坚持教义后如何获取所有ID?
【发布时间】:2023-03-28 11:57:01
【问题描述】:

我正在使用批处理来提高我的性能。这意味着我在制作 50 之后插入我的对象,就像您在代码中看到的那样。但是我需要恢复这些对象的所有 ID,因为我需要保存一些照片。 (我用ID来命名照片)

    ...

    $em->persist($contact);

                    if(($k % $batchsize)===0){
                        $em->flush();
                        $user_id=$user->getId();
                        $em->clear();
                        $user=$userManager->findById($user_id);
                    }
                    $k++;
}

有谁知道在完成此过程后如何恢复 ID?

【问题讨论】:

    标签: php symfony orm doctrine-orm


    【解决方案1】:

    好的,在您发表评论后:

    我建议你创建一个 postFlush 监听器。这样,您可以检索插入的所有实体并使用这些实体:

    namespace AppBundle\EventListener
    
    use Doctrine\ORM\Event\LifecycleEventArgs;
    use AppBundle\Entity\Contact;
    
    class ContactInserts {
        public function postFlush(LifecycleEventArgs $args) {
            $em = $args->getEntityManager();
            foreach ($em->getUnitOfWork()->getScheduledEntityInsertions() as $entity) {
                if ($entity instanceof Contact) {
    
                    //... Do what you want to do with your contact ($entity) ...
                    $em->persist($entity);
                }
            }
            $em->flush();
        }
    }
    

    在你的service.yml 或`config.yml̀

    services:
        my.listener:
            class: AppBundle\EventListener\ContactInserts
            tags:
                - { name: doctrine.event_listener, event: postFlush }
    

    但请注意,因为您在下面的代码中存在一些逻辑问题:

    ...            
    $em->persist($contact);
    // /!\ If you don't have a 49 contacts left, these won't be flushed
    if(($k % $batchsize)===0) {
         $em->flush();
         $em->clear();
         /* I can't understand what you're doing here sorry */
         $user_id=$user->getId(); //You use user to get the id
         $user=$userManager->findById($user_id); //You use the just retrieved id to get the user ???                   
    }
    $k++;
    

    【讨论】:

    • 我想要联系人 ID。因为联系人的所有者是用户,所以用户 ID 始终相同。我无法获取联系人 ID,因为一旦将联系人插入 DDBB,就会生成联系人 ID。我没有设置所有代码,因为很长,我认为代码足以理解逻辑,非常抱歉,感谢您的回答:)
    • 我用一个更适合您的问题的解决方案更新我的答案;)
    • 我知道,但是循环之后还有另一个刷新。但是,我必须将侦听器放在哪里才能使此功能起作用。你能用导入和命名空间写完整的脚本吗?
    • 我太客气了。但在这里。 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    相关资源
    最近更新 更多