问题
I have a table Object that has 2 fields that are foreign keys (user_id and teacher_id). After generating the Entities for the X table, the entity only contain the $user and $teacher properties, which forces me to use the associated objects instead of id. So supposing I know the user_id and teacher_id for my object, instead of doing:
$object->setUserId(1)
I have to do:
$user = $this->getDoctrine()->getRepository('MyBundle:Users')->find(2);
$object->setUser($user)
is there no way to work directly with the ids to avoid retrieving the entire object associated to each id?
回答1:
The framework suggests to use objects when setting the association value. Still – are you sure the record isn't loaded in the memory already? If it is, it will not cause additional SQL statement execution.
If you really need to update the association without loading the object, you can
- run native SQL;
- try creating Doctrine Proxy object manually and setting it instead.
You can get the proxy object using EntityManager
method getReference
:
$object->setUser($this->getDoctrine()->getReference('MyBundle:Users', 2));
来源:https://stackoverflow.com/questions/13007843/set-doctrine2-entity-property-without-retrieving-entire-associated-object