NOTE: Topic is lengthy but detailed and may come in handy if you use Doctrine2 and oneToOne relationships.
Recently I came across a problem in Doctrine:
This is a known issue for OneToOne associations. There is a github discussion about this that is worth reading. A solution (pull request) was proposed and rejected.
Your question suggests the same solution proposed by the contributors to Doctrine: change the owning side of the relationship.
I had a similar problem with an entity called Version
that had a OneToOne
bidirectional relationship with Settings
. Every time I queried Version
(say for 10 specific version records), Doctrine would do additional queries for the joined Settings
(as if it was Lazy Loading these entities). This happened, even though I did not reference Settings
anywhere, e.g. $Version->getSettings()->getSomeProperty()
.
The only "solution" (hack) that works for me is to manually included a JOIN for this Settings
entity every time I did a query on Version
. But since I don't need the extra entity (in this case), that would still be a single extra unnecessary query, every time I query this table in different ways.
Based on other suggestions, I thought that if I explicitly specified this relationship as "extra lazy" it would work, e.g.
/**
* @ManyToMany(targetEntity="Settings", mappedBy="version", fetch="EXTRA_LAZY")
*/
But this doesn't affect hydration. See the Doctrine Docs for more details about what EXTRA_LAZY
does.
What helped in my case (when I didn't need an entity), was to specify that I wanted to fetch as an array (rather than object).
$query = $queryBuilder->getQuery();
$query->getResult(Query:HYDRATE_ARRAY);
This returns an array, and as a result it doesn't lazy load the OneToOne associations. However, in other contexts where I need the entity object, I had to explicitly JOIN the entity (despite not wanting it).