我有一個類似的問題和數據庫結構:原則2 與條件的關聯映射但是,我需要具有批準評論的文章集合:如何做沒有N + 1的協商映射?$articles = $repository->findAllArticlesWithApprovedComments(); Foreach($articles as $article){ $article->getTitle(); foreach($article->getAprovedComments() as $comment){ $comment->getText(); } }標準有效,如果我使用延遲加載,但它的N + 1問題。如果我使用預先加載(加入并添加選擇) - 條件不起作用。如果我使用此代碼:$articles = $em->createQueryBuilder() ->from(Article::class,'article') ->leftJoin('article.comments','comments') ->addSelect('article') ->addSelect('comments') ->andWhere('comments.approved= :ap ') ->setParameter('ap',true) ->getQuery()->getResult();我會收到有批準評論的文章,但如果文章有0條評論,它將不會落入文章集合。如何獲取具有已批準評論的文章,但如果文章中沒有評論,則文章仍保留在集合中?示例:我在 DB 中有:Article1: [approvedComment, nonAprovedComment]Article2: [nonAprovedComment]Article3: [approvedComment]我需要結果(帶有原則,代碼中的非過濾器):Article1: [approvedComment]Article2: []Article3: [approvedComment]
1 回答

萬千封印
TA貢獻1891條經驗 獲得超3個贊
可以使用條件而不是條件在數據庫級別篩選集合。join
where
然后,您的查詢將如下所示:
$articles = $em->createQueryBuilder() ->from(Article::class, 'article') ->leftJoin('article.comments', 'comments', 'WITH', 'comments.approved = :ap') ->addSelect('article') ->addSelect('comments') ->setParameter('ap', true) ->getQuery()->getResult();
由于這是左聯接,因此它將返回所有文章,即使它們沒有任何批準的注釋。
- 1 回答
- 0 關注
- 79 瀏覽
添加回答
舉報
0/150
提交
取消