In my sonata comments table it is possible to see all comments with its authors. I'd like to order them after :
user_id (Author) | comment |
Erik | 1 |
Lisa | 2 |
Jose | 3 |
Erik | 4 |
Lisa | 5 |
Erik | 6 |
output should be:
user_id (Author) | comment |
Erik | 1 |
Erik | 4 |
Erik | 6 |
Lisa | 2 |
Lisa | 5 |
Jose | 3 |
I was able to solve it in SQL:
SELECT
user_comment.*, counter.count
FROM
user_comment
LEFT JOIN (
SELECT
user_comment.user_id, count(user_comment.user_id) as count
FROM
user_comment
GROUP BY
user_comment.user_id
) counter ON counter.user_id = user_comment.user_id
ORDER BY counter.count DESC, username ASC
I can't find a way get this solution with the query builder, because it's not supporting subquery that way and it firsts executes the selects, then from, then join and so on.
For instance that won't work because the order of the qb is fixed:
$qb->select('counter')
->addSelect('count(counter.user) as count')
->from('App\Entity\UserComment', 'counter')
->groupBy('counter.user')
->leftJoin('App\Entity\UserComment', 'cm', Join::WITH,$rootAlias.'.user = cm.user')
->orderBy('count', 'DESC');