I have two entities
Article has a relation to user named 'likedByUsers'
Now, I would like to get the articles order by number of likes, but:
what I currently have is this:
$builder = $this->createQueryBuilder('a');
->select('COUNT(u) AS nbrLikes')
->leftJoin('a.likedByUsers', 'u')
->orderBy('nbrLikes', 'DESC')
->groupBy('a.id')
->getQuery()
->getResult()
;
this correctly returns the number of likes (with 0 for articles without likes), but it does NOT return the Articles themselves
I've tried adding
->select('a, COUNT(u) AS HIDDEN nbrLikes')
but it fails because a
is not part of the GROUP BY
any ideas ?
If you want to select "multiple" values you need to specify them into select method of query builder. Just like reported below
$builder = $this->createQueryBuilder('a')
->select('COUNT(u) AS HIDDEN nbrLikes', 'a.id')
->leftJoin('a.likedByUsers', 'u')
->orderBy('nbrLikes', 'DESC')
->groupBy('a.id')
->getQuery()
->getResult();
You have to remember that result will not be an entity but an associative array
If you want full entity
$builder = $this->createQueryBuilder('a')
->select('COUNT(u) AS HIDDEN nbrLikes', 'a')
->leftJoin('a.likedByUsers', 'u')
->orderBy('nbrLikes', 'DESC')
->groupBy('a')
->getQuery()
->getResult();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With