0

I am working with Symfony 3 (with Doctrine and FosRestBundle) and I've been trying to find a way to, by default, not retrieve entity relationships when querying an entity. Instead I'm aiming to opt into joins for finer control over what data is returned based on context.

For example, say I have a Post entity with One-To-Many relationships to Comments and Tags, I want to by default, when querying the Post entity, not return the nested comments or tags. My current repository query looks as simple as;

$query = $this->createQueryBuilder('p');

return $query->getQuery()->getResult();

This however returns the nested entities. What I need is the ability to opt into the linked entities by manually adding a join statement. Is this possible? Thanks!

Chris
  • 1
  • 1
  • 1
    I'm pretty sure you are describing the default behavior of Doctrine already. when you say that it "returns the nested entities" how are you checking that? Are you observing actual queries to the DB or are you doing something like `$post->getComments()` and noting that it returns results? If the latter, you are unknowingly triggering a second query. A second questions is why are you concerned about it? – craigh Mar 22 '16 at 00:27
  • @craigh is right, this is the default doctrine behaviour unless you have fetch="eager" on – Richard Mar 22 '16 at 01:44
  • @craigh I check the return value from that above code and it contains an array of Post entities, with no nested associations as expected. I believe the issue seems to be in the JMS serializer, which appear to call the getters on the entity, which in turn loads the relationships. – Chris Mar 22 '16 at 09:51
  • @Richard yeah this is what I want and expect, however at the point of serialisation (to return the JSON response from the API) all relationships have been retrieved. I can only guess that JMS Serializer is calilng the getters on the entities, which in turn lazy loads the relationships – Chris Mar 22 '16 at 09:52
  • @Chris gotcha - this might be useful: http://stackoverflow.com/questions/11851197/avoiding-recursion-with-doctrine-entities-and-jmsserializer – Richard Mar 22 '16 at 18:28

0 Answers0