John
John

Reputation: 13

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.

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();
 }

Upvotes: 0

Views: 2334

Answers (1)

SpicyTacos23
SpicyTacos23

Reputation: 550

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.

$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.

Upvotes: 1

Related Questions