set Doctrine2 entity property without retrieving entire associated object

一世执手 提交于 2019-12-11 03:32:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!