Let’s say I have two entities with a one to many relationship. Call them EntityOne and EntityMany.
I want to save an EntityMany to the database.
I don’t have an instance of EntityOne but I know the required entity_one_id.
Is there a way to save EntityMany without retrieving an instance of EntityOne from the db?
I don’t want to do anything with the saved EntityMany. I just want to save it.
The only way I’ve been able to save EntityMany in this situation is to retrieve the EntityOne from the db, do a $entity_many->setEntityOne($entity_one) and then persist EntityMany.
That works but it seems like an unnecessary query for EntityOne when all the db needs is the id.
I tried simply instantiating a new EntityOne() and setting the id (I had to add a setter for the auto-generated integer id) and then using that unsaved instance but Doctrine was not happy with several errors.
EntityManager has a method “getReference” – you can use it to achieve your goal. It should look something like that:
Look here:
http://docs.doctrine-project.org/en/latest/reference/configuration.html#proxy-objects