Matt
Matt

Reputation: 2843

Doctrine2 & Symfony2: Reset ID value on save when in foreach loop

See the following code:

$passwords = array('aaaa', 'bbbb', 'ccccc', 'dddd', 'eeeee');

$em = $this->getDoctrine()->getEntityManager();
$foo = new Foo();
$foo->setName('Joe Bloggs');
$foo->setTitle('Mr');
foreach ($passwords as $password) {
    $foo->setPassword($password);
    $em->persist($foo);
    $em->flush();
}

Here when I try to save the $foo object, i'd hope to save it X number of times, where X is the length of $passwords, however it just inserts the value once, then updates it the other 4 times.

Does anybody know how I can achieve this so that it inserts the record 5 times.

Thanks

Upvotes: 1

Views: 563

Answers (1)

AlterPHP
AlterPHP

Reputation: 12727

The choice between creation and update is made on the object identification :

  • new object => creation
  • existing object => update

So, don't try to optimize treatment by not repeating setName and setTitle, but you can execute flush() only once ;) :

$passwords = array('aaaa', 'bbbb', 'ccccc', 'dddd', 'eeeee');

$em = $this->getDoctrine()->getEntityManager();
foreach ($passwords as $password) {
    $foo = new Foo();
    $foo->setName('Joe Bloggs');
    $foo->setTitle('Mr');
    $foo->setPassword($password);
    $em->persist($foo);
}
$em->flush();

Upvotes: 3

Related Questions