Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 原则2,与条件的关联映射_Php_Symfony_Doctrine - Fatal编程技术网

Php 原则2,与条件的关联映射

Php 原则2,与条件的关联映射,php,symfony,doctrine,Php,Symfony,Doctrine,我有一个类似的问题和数据库结构: 但是,我需要一系列带有批准评论的文章: 如果没有N+1,如何进行关联映射 $articles = $repository->findAllArticlesWithApprovedComments(); Foreach($articles as $article){ $article->getTitle(); foreach($article->getAprovedComments() as $commen

我有一个类似的问题和数据库结构:

但是,我需要一系列带有批准评论的文章:

如果没有N+1,如何进行关联映射

$articles = $repository->findAllArticlesWithApprovedComments();

    Foreach($articles as $article){
       $article->getTitle();
       foreach($article->getAprovedComments() as $comment){
           $comment->getText();
       }
    }
如果我使用延迟加载,则条件是有效的,但这是N+1问题。如果我使用即时加载(join和addSelect)-标准不起作用

如果我使用此代码:

$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]
我需要结果(有条令,无代码过滤):


您可以使用
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();

由于这是一个左联接,因此它将返回所有文章,即使它们没有任何已批准的评论。

您可以使用
联接
而不是
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();

由于这是一个左加入,它将返回所有文章,即使它们没有任何经批准的评论。

谢谢,我将尝试您的答案!向上箭头)谢谢,我会试试你的答案!(向上箭头)