Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add element to doctrine ArrayCollection by Id

I find very annoying to have to fetch an object by id from database every time I want to add it to a relationship. Is there a way to add an object to a a relationship by id instead of adding the whole object?

This is my actual code:

...
$person = $em->getRepository("Person")->findOneById($id);
$me->getPersons()->add($person);
...

I would like to have something like this:

...
$me->getPersons()->add($id);
...

Then I would be saving one trip to the database! Which I like better! Is it possible?

like image 636
danielrvt Avatar asked Oct 18 '25 23:10

danielrvt


1 Answers

You don't have to do that actually. You can get reference object like so:

$person = $em->getReference("Person", $id);
$me->getPersons()->add($person);

Doctrine will not make a query for Person but will instead return an reference proxy object for person with that id. If you, however do:

$person = $em->getReference("Person", $id); // 0 queries
$person->getId(); // Still 0 queries
$person->getSomeField(); // query fired

Doctrine will trigger lazy load if you try to get some field that has to be fetched from database.

See docsEntityManager::getReference method

like image 146
Igor Pantović Avatar answered Oct 21 '25 14:10

Igor Pantović