Doctrine 2 DQL - how to select inverse side of unidirectional many-to-many query?

前端 未结 5 1154
南笙
南笙 2020-12-23 21:53

I have two classes - Page and SiteVersion, which have a many to many relationship. Only SiteVersion is aware of the relationship (because the site is modular and I want to b

5条回答
  •  情深已故
    2020-12-23 22:29

    There's two ways of handling this in Doctrine ORM. The most typical one is using an IN condition with a subquery:

    SELECT
        p
    FROM
        SitePage p
    WHERE
        p.id IN(
            SELECT
                p2.id
            FROM
                SiteVersion v
            JOIN
                v.pages p2
            WHERE
                v.id = :versionId
                AND
                p.slug = :slug
        )
    

    The other way is with an additional join with the arbitrary join functionality introduced in version 2.3 of the ORM:

    SELECT
        p
    FROM
        SitePage p
    JOIN
        SiteVersion v
    WITH
        1 = 1
    JOIN
        v.pages p2
    WHERE
        p.id = p2.id
        AND
        v.id = :versionId
        AND
        p2.slug = :slug
    

    The 1 = 1 is just because of a current limitation of the parser.

    Please note that the limitation that causes the semantical error is because the hydration process starts from the root of the selected entities. Without a root in place, the hydrator has no reference on how to collapse fetch-joined or joined results.

提交回复
热议问题