【问题标题】:(Doctrine with Symfony 4) Aggregate functions along with a regular DQL statement?(Symfony 4 的原则)聚合函数和常规 DQL 语句?
【发布时间】:2019-05-30 17:07:39
【问题描述】:

我有以下 DQL 语句,使用 Doctrine 的查询构建器:

如您所见,我将带回所有帖子及其 cmets:

public function getAllPosts(User $user){

    $qb = $this->createQueryBuilder('p');
    $qb->select('p, postPhotos,postVideos, comments, commentUser, commentUserPhoto, replyComments, commentReplyUser, commentReplyUserPhoto, postTier,creator,creatorPhoto,creatorTiers,creatorSubscriptions')
        ->leftJoin('p.photos', 'postPhotos')
        ->leftJoin('p.videos', 'postVideos')
        ->leftJoin('p.comments', 'comments')
        ->leftJoin('comments.user', 'commentUser')
        ->leftJoin('commentUser.photos', 'commentUserPhoto', 'WITH', 'commentUserPhoto.type = :profileType')
        ->leftJoin('comments.children', 'replyComments')

我已经尝试添加一个

->addSelect("COUNT(p.comments) as countComments")

我只是得到一个错误,“countComments' 不指向一个类”

所以我查找了其他参考资料,例如:https://symfonycasts.com/screencast/doctrine-queries/select-sum

但它没有给出如何在 DQL 查询结果中包含计数的示例。

我是否只需要在 cmets 存储库中创建自己的计数函数,并遍历我的原始数据集,每个帖子调用一次?

【问题讨论】:

    标签: count aggregate dql


    【解决方案1】:

    您正在尝试做的事情有 2 个问题:

    1) 您应该在聚合函数中使用连接别名“cmets”,而不是关系字段“p.cmets”:

    ->addSelect("COUNT(comments) as countComments")
    

    并且查询将按根实体分组,除非指定了->groupBy()

    但这不是你的解决方案,真正的问题是:

    2) 当您尝试聚合表格的任何字段时,您不能选择表格的字段。它不起作用并且会产生奇怪的结果。更具体地说,您只会在结果集中获得一个实体。

    更多why cant you mix aggregate values and non aggregate values in a single select

    解决方案

    由于您已经选择了“cmets”,因此只需“count”收集结果:

    $posts = $queryBuilder->getQuery()->getResult();
    foreach($posts as $post) {
        echo $post->getComments()->count();
    }
    

    $posts = $queryBuilder->getQuery()->getArrayResult();
    foreach($posts as $post) {
        echo count($post['comments']);
    }
    

    参考资料:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-08
      • 2019-10-23
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多