有没有可能在教义2中使用关联而不是代理类获得“完整”对象?序列化代理类学说2
因为我正在序列化实体(和关系),但是当我反序列化时,我只是返回一个代理类。
查询我做:
public function getSnippet($id)
{
return $this->getEntityManager()->getRepository('GvnSnippetryBundle:Snippet')->findOneBy(array('id' => $id));
}
有没有可能在教义2中使用关联而不是代理类获得“完整”对象?序列化代理类学说2
因为我正在序列化实体(和关系),但是当我反序列化时,我只是返回一个代理类。
查询我做:
public function getSnippet($id)
{
return $this->getEntityManager()->getRepository('GvnSnippetryBundle:Snippet')->findOneBy(array('id' => $id));
}
从未尝试过的是个人(和在指尖没有Doctrine2),但marking association as EAGER
应该做的伎俩。 Hovewer,你总是会这样加载这些关联的对象。
作为一种解决方法,请尝试在序列化之前访问关联的实体。例如。如果您已按照建议来封装关联对象集合(并且您确实应该遵循它),那么只需使用$snippet->howDidYouCallFunctionThatReturnCollection()
即可访问它。 Doctrine拦截对Collection
检查的请求,其中填充代理并自动加载。所以,它应该是这样的:
class Snippet{
//other declarations
/** OneToMany(targetEntity='Blah', ...)*/
protected $associations;
public function getAssociations(){
return $this->associations; //fills proxies with real data here
}
}
public function getSnippet($id)
{
$snippet = $this->getEntityManager()->getRepository('GvnSnippetryBundle:Snippet')->findOneBy(array('id' => $id));
$snippet->getAssociations(); //gets only one association
$snippet->getAssociations2(); //and so on
return $snippet;
}
请注意,这是没有办法完整的代码示例,但我假设你知道如何映射关联。无论如何,请查看Working with Objects和Association Mapping章节以获取更详细的说明和代码示例。
J0HN的回答很好。
如果您希望更专注,可以通过创建自定义查询(直接在DQL中或使用QueryBuilder)来强制Doctrine访存关联实体。要强制协会被加载,你既需要:
1)加入相关的实体 2)参考该实体在SELECT
所以,在DQL:
SELECT f
FROM Foo f
JOIN f.Bar b
这将不加载相关的酒吧,因为它不是在SELECT引用的 - 你会得到一个代理来代替,而
SELECT f, b
FROM Foo f
JOIN f.Bar b
将强制学说取得 - 加入你的酒吧。
HTH
哦谢谢你的提示!正是我需要的! –