Reputation: 8164
I would like to be able to set a foreign key just by its id.
Sometimes, for some long scripts, the fact that I need to give the full foreign object to my setter method force me to do some database queries, wasting resources.
$entity = new SomeEntity();
$entity->setIdAnswer(42);
$em->persist($entity);
Instead of
$world = $em->getRepositorye('My/Bundle:Answer')->findOneById(42);
$entity = new SomeEntity();
$entity->setIdAnswer( $world );
$em->persist( $entity);
How is it possible to occasionally set the foreign key with its integer key?
It would be great if we can do that without using some dirty code
Upvotes: 1
Views: 269
Reputation: 2191
Usually you can achieve exactly that with reference proxies: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/advanced-configuration.html#reference-proxies
// $em instanceof EntityManager, $cart instanceof MyProject\Model\Cart
// $itemId comes from somewhere, probably a request parameter
$item = $em->getReference('MyProject\Model\Item', $itemId);
$cart->addItem($item);
Upvotes: 3