Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transactions and symfony2 entity manager

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

like image 592
Matt Welander Avatar asked Aug 16 '12 21:08

Matt Welander


People also ask

What is a Symfony entity?

Well, entity is a type of object that is used to hold data. Each instance of entity holds exactly one row of targeted database table. As for the directories, Symfony2 has some expectations where to find classes - that goes for entities as well.

What is Symfony ORM?

Symfony provides all the tools you need to use databases in your applications thanks to Doctrine, the best set of PHP libraries to work with databases. These tools support relational databases like MySQL and PostgreSQL and also NoSQL databases like MongoDB.

How should be the process to add a new entity to the app in Symfony?

With the doctrine:database:create command we create a new database from the provided URL. With the make entity command, we create a new entity called City . The command creates two files: src/Entity/City. php and src/Repository/CityRepository.

What is doctrine repository?

A repository in a term used by many ORMs (Object Relational Mappers), doctrine is just one of these. It means the place where our data can be accessed from, a repository of data. This is to distinguish it from a database as a repository does not care how its data is stored.


1 Answers

try {
    $em->getConnection()->beginTransaction();

    // do your thing here

    $em->getConnection()->commit();
} catch (\Exception $e) {
    $em->getConnection()->rollback();
    throw $e;
}
like image 143
Elnur Abdurrakhimov Avatar answered Sep 28 '22 19:09

Elnur Abdurrakhimov