设置Doctrine2实体属性,而不检索整个关联对象 [英] set Doctrine2 entity property without retrieving entire associated object

查看:149
本文介绍了设置Doctrine2实体属性,而不检索整个关联对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表对象,其中有2个字段是外键(user_id和teacher_id)。在为X表生成实体后,实体只包含$ user和$ teacher属性,这迫使我使用关联对象而不是id。所以假设我知道我的对象的user_id和teacher_id,而不是这样做:

  $ object-> setUserId(1)

我必须这样做:

  $ user = $ this-> getDoctrine() - > getRepository('MyBundle:Users') - > find(2); 
$ object-> setUser($ user)

是否有办法直接工作使用ids来避免检索与每个id相关联的整个对象?

解决方案

框架建议在设置关联值时使用对象。还是 - 你确定记录没有加载在内存中吗?如果是,则不会导致额外的SQL语句执行。



如果您真的需要更新关联而不加载对象,则可以




  • 运行本地SQL;

  • 尝试手动创建Doctrine Proxy对象,并将其设置为



您可以使用 EntityManager 方法获取代理对象 getReference

  $ object-> setUser($ this-> getDoctrine() - > getReference('MyBundle:Users' ,2)); 


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?

解决方案

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));

这篇关于设置Doctrine2实体属性,而不检索整个关联对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆