transactions and symfony2 entity manager
Asked Answered
F

2

8

Is there a way to manually specify transactions in symfony2 with the entity manager (doctrine), or perhaps a natural way of accomplishing in a single transaction what I am doing below in two?

// creating screen object...
//Creating user object...

        //flush the screen into database in order to get the Id to relate the server (user) to
        $em->persist($screen);
        $em->flush();

        //Get id of just inserted screen and attach that to new server (user)
        $tempRecordId = $screen->getId();
        $tempEntity = $em->getRepository('BizTVContainerManagementBundle:Container')->find($tempRecordId);
        $entity->setScreen($tempEntity);

        //Flush the user also into database
        $em->persist($entity);
        $em->flush();

See I must flush my first entity in order to get it's ID out, so I can relate my second entity to my first...

Fontanez answered 16/8, 2012 at 21:55 Comment(0)
F
7

Why don´t you just do:

// creating screen object...
//Creating user object...
    $entity->setScreen($screen);
    $em->persist($screen);
    $em->persist($entity);
    $em->flush();
Footstalk answered 16/8, 2012 at 22:24 Comment(1)
Had no idea it was that easy! I guess I was making it more complicated than it needed to be huh!Fontanez
B
23
try {
    $em->getConnection()->beginTransaction();

    // do your thing here

    $em->getConnection()->commit();
} catch (\Exception $e) {
    $em->getConnection()->rollback();
    throw $e;
}
Bromo answered 17/8, 2012 at 7:20 Comment(1)
@Elnur, is $em->getConnection(), you miss the (), thanks anywayNosing
F
7

Why don´t you just do:

// creating screen object...
//Creating user object...
    $entity->setScreen($screen);
    $em->persist($screen);
    $em->persist($entity);
    $em->flush();
Footstalk answered 16/8, 2012 at 22:24 Comment(1)
Had no idea it was that easy! I guess I was making it more complicated than it needed to be huh!Fontanez

© 2022 - 2024 — McMap. All rights reserved.