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

前端 未结 5 1149
南笙
南笙 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:18

    I couldn't figure out how to get native queries working, so have resolved in a slightly hacky way:

    $id = $em->getConnection()->fetchColumn("SELECT
        pages.id
        FROM
        pages
        INNER JOIN siteversion_page ON siteversion_page.page_id = pages.id
        INNER JOIN siteversions ON siteversion_page.siteversion_id = siteversions.id
        WHERE siteversions.id = 1
        AND pages.slug = 'index'");
    
    $page = $em->find('Page', $id);
    

    I don't like it because it results in more queries to the database (especially if I need to fetch an array of pages instead of one) but it works.

    Edit: I've decided to just go with a class for the association. Now I can do this query:

    SELECT p FROM Page p, SiteVersionPageLink l
    WHERE l.page = p AND l.siteVersion = 5 AND p.slug = 'index'
    

提交回复
热议问题