Question

Using Doctrine 2 with Zend Framework 2. Been thinking of how I am meant to persist an entity with a field having a Many-To-One association with another entity that already exists in the database. Would I have to fetch the inverse side from the database first and then adding it to the owning Entity before persisting to the database as in the code below.

//$data = $_POST;
$book = new Book();
$author = $em->getRepository('Application\Entity\Book')->find($data['author_id']);

$book->setTitle($data['title'])
    ->setISBN($data['title'])
    ->setAbstract($data['abstract'])
    ->setYear($data['year'])
    ->setAuthor($author);

$em->persist($book);
    $em->flush();

Normally, without using doctrine, all I have to do is update the author_id field of the Book entity above and persist to the Database. But now I have to make a trip to the Database to fetch the author details to create the entity and thus the association and then persist.

Is this the way it should be done or there is another way that doesnt involve fetching the author's details.

Was it helpful?

Solution

As you can read here

The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database. This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier.

You could simply do this:

$book = new Book(); 
$book->setAuthor( $em->getReference('Application\Entity\Author',$data['author_id']));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top