Question

I have an entity Dog with OneToOne relation to Collar.

Say I create a new Dog entity and I have the Collar id I want to relate to it. Not the Collar object itself, only it's id number.

$collar = 12;
$dog = new Dog();
$dog->setCollar(?);

Do I need to actually fetch the Collar object from the DB, only to set it's id (which is already given), or is there a way to create a proxy Collar object?

Was it helpful?

Solution

Yes there actually is

You can use your entity manager to get a Proxy Reference instead of an actual Entity which just gives you a proxy object representing the Entity without actually fetching it from the database.

Check the code below for an example

$collarId = 12;

// First param is the Entity classname, second is the Entity id
$collar = $entityManager->getReference('Collar', $collarId); 

$dog = new Dog();
$dog->setCollar($colar);

$entityManager->persist($dog);
$entityManager->flush();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top