Primary key of owning side as a join column

后端 未结 4 710
借酒劲吻你
借酒劲吻你 2020-12-02 15:06

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:

4条回答
  •  一生所求
    2020-12-02 15:16

    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.

    Recommendation

    Your question suggests the same solution proposed by the contributors to Doctrine: change the owning side of the relationship.

    Other Options Explored

    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().

    Manual JOIN

    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.

    Extra Lazy

    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.

    Hydration Type: HYDRATE_ARRAY

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

提交回复
热议问题