0

I have Post entity. Post entity have one Category, many Tags and many Comments.

How to get 'most commented posts' ordered by most commented?

When I am doing this:

$query = $this->createQueryBuilder('post')
    ->addSelect('COUNT(comments.id) AS HIDDEN comments_num')
    ->innerJoin('post.comments', 'comments')
    ->groupBy('post.id')
    ->orderBy('comments_num', 'DESC')
    ->addOrderBy('post.created', 'DESC')
    ->getQuery()
;

it is working but Doctrine makes so many queries, but the problem is the more comments the more queries *times something... It cant be that way. On the page with this query results I have 71 queries and the number of them grows with commented posts number.

When I am doing the same but adding left joining and selecting category, tags and comments there... queries number is low and independent from comments number but when I pass that query to Paginator it gets kind of empty pages after few pages with results...

$query = $this->createQueryBuilder('post')
    ->addSelect('category, tags, comments')
    ->addSelect('COUNT(c) AS HIDDEN comments_num')
    ->innerJoin('post.comments', 'c')
    ->innerJoin('post.comments', 'comments')
    ->leftJoin('post.category', 'category')
    ->leftJoin('post.tags', 'tags')
    ->groupBy('post.id')
    ->addGroupBy('tags.id')
    ->addGroupBy('comments.id')
    ->orderBy('comments_num', 'DESC')
    ->addOrderBy('post.created', 'DESC')
    ->getQuery()
;

query will be passed to Paginator so it must be build in DQL or using QueryBuilder.

edit: I think there is a bug in Paginator, because... When I dump that second query results I am getting good results in array collection of 12. But when I pass that query to Paginator and then call Paginator.count() I get results: 55 :D when there are 44 posts in test database :)

1
  • I think i could help you but to be sure what doctrine does it would be helpful if you could add the DQL-String (...->getQuery()->getDQL()) to your question. As far as i know, doctrine allways creates a DQL even when using the QueryBuilder and then transforms that to SQL... May 7, 2021 at 7:30

1 Answer 1

0

In The first moment Write your query just with SQL, after do you can execute pure SQL in doctrine.

After you try convert your SQL for DQL

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.