简体   繁体   English

[Doctrine2]如何计算“帖子”的“评论”中的“喜欢”数量

[英][Doctrine2]How to count the amount of “likes” in the “comment” of a “post”

I'm struggling with my own social network where i'm trying to sort the comments of a post by the amount of likes on them. 我在自己的社交网络中苦苦挣扎,在该社交网络中,我尝试按对他们的喜欢程度对帖子的评论进行排序。 So i made three tables : a Post with many Comments and a Comment with many Likes. 所以我做了三个表:一个带有很多评论的帖子和一个带有很多赞的评论。 Of course, there's a User table to handle all of this. 当然,有一个User表来处理所有这些。

public function loadProfilePost($user, $first = 0, $limit = 0)
{
    $q =    $this->_em->createQueryBuilder()
            ->select('post, comment')
            ->from('EvoSocialBundle:Post', 'post')
            ->leftJoin('post.comments', 'comment')
            ->where('post.user = :user')
            ->setParameter(':user', $user)
            ->addOrderBy('post.created', 'DESC');

    $q->setFirstResult($first);
    if($limit > 0)
        $q->setMaxResults($limit);

    return $q->getQuery()->getResult();
}

To sort comments by its count of likes you can add one more join in your query builder with likes entity then set group by criteria like group by post.id,comments.id , i have added addSelect() with count function to count the likes for comment and setting the result of count AS HIDDEN so that they will not be returned with the result set and will affect only the query builder part 要按其喜欢计数对评论进行排序,您可以在查询构建器中添加一个具有“喜欢”实体group by post.id,comments.id然后按group by的标准设置group by post.id,comments.id ,我添加了带有count函数的addSelect()来计算喜欢进行注释并设置count AS HIDDEN的结果,以便它们不随结果集一起返回,并且仅影响查询构建器部分

public function loadProfilePost($user, $first = 0, $limit = 0)
{
    $q =    $this->_em->createQueryBuilder()
            ->select('p, c')
            ->addSelect('COUNT(DISTINCT  c.id) AS HIDDEN total_likes')
            ->from('EvoSocialBundle:Post', 'p')
            ->leftJoin('p.comments', 'c')
            ->leftJoin('c.likes', 'l')
            ->where('p.user = :user')
            ->setParameter(':user', $user)
            ->groupBy('p.id')
            ->addGroupBy('c.id')
            ->orderBy('total_likes','DESC');

    $q->setFirstResult($first);
    if($limit > 0)
        $q->setMaxResults($limit);

    return $q->getQuery()->getResult();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM