Reputation: 3143
Is there a possibility to get the "full" object with associations instead of the proxy classes in doctrine 2?
Because I'm serializing the entity (and relations) but when I deserialize I just get a proxy class back.
The query I'm doing:
public function getSnippet($id)
{
return $this->getEntityManager()->getRepository('GvnSnippetryBundle:Snippet')->findOneBy(array('id' => $id));
}
Upvotes: 1
Views: 2196
Reputation: 62894
J0HN's answer is good.
If you want to be more focused, you can force Doctrine to fetch-join the associated entities by creating a custom query (either directly in DQL, or using the QueryBuilder). To force the association to be loaded, you need both:
1) Join the associated entity 2) Reference that entity in the SELECT
So, in DQL:
SELECT f
FROM Foo f
JOIN f.Bar b
This will not load the associated Bar, since it's not referenced in the SELECT -- you'll get a proxy instead, while
SELECT f, b
FROM Foo f
JOIN f.Bar b
will force doctrine to fetch-join your Bars.
HTH
Upvotes: 2
Reputation: 26941
Never tried that personally (and don't have Doctrine2 at fingertips), but marking association as EAGER
should do the trick. Hovewer, you'll always load those associated object this way.
As a workaround, try accessing the associated entities before serializing. E.g. if you have followed the advice to encapsulate associated objects collection (and you really should follow it), you just access it with $snippet->howDidYouCallFunctionThatReturnCollection()
. Doctrine intercepts the request to the Collection
checks that it's filled with proxies and load it automatically. So, it should be something like:
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;
}
Note that it's no way a complete code sample, but I assume you know how to map associations. Anyway, review Working with Objects and Association Mapping chapters for more detailed description and code samples.
Upvotes: 1