简体   繁体   English

使用 Doctrine 持久化多个实体

[英]persist multiple entities with Doctrine

I have pulled out collection of arrays that I need to post in my database.我已经提取了需要在我的数据库中发布的数组集合。 It works.有用。

Now, I need to persist more then one row and I am trying to do it with foreach loop but it doesn't work.现在,我需要坚持多于一行,我正在尝试使用 foreach 循环来做到这一点,但它不起作用。

My part of code:我的部分代码:

$dataset = array();

            foreach ($dataset as $data) {

                $a = new User();

                $a->setFirstName($data[3]);
                $a->setLastName($data[5]);
                $a->setUsername($data[13]);
                $a->setEmail($data[14]);
                $a->setCompany($data[23]);

                $this->em->persist($a);
                $this->em->flush();
 }

Looks like you're closing the connection after the flush.看起来您在刷新后关闭了连接。 Try to load and persist the object inside the foreach loop and then flush outside just one time.尝试在 foreach 循环内加载并持久化对象,然后只刷新一次。

$dataset = array();

        foreach ($dataset as $data) {

            $a = new User();

            $a->setFirstName($data[3]);
            $a->setLastName($data[5]);
            $a->setUsername($data[13]);
            $a->setEmail($data[14]);
            $a->setCompany($data[23]);

            $this->em->persist($a);
        }

        $this->em->flush();

The EntityManager represents the connection so you just need to flush when you are ready to commit to the DB. EntityManager 代表连接,因此您只需要在准备提交到数据库时刷新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM