简体   繁体   中英

Doctrine2 order by count many to many with many left join

I have an entity Book and it has too many relations with other entities. now I want to sort a COUNT column of one of many to many relation properties and I use this approach

but it gave me a wrong response:

  • It shows me only one row from any of my join entity because it group by a book id
  • Count number is wrong because it count all join rows so number is very large usually

this happen because I have too many left join in my query builder like this:

$this->createQueryBuilder('b')
        ->addSelect('bookTranslations')
        ->addSelect('bookGenres')
        ->addSelect('bookCrews')
        ->addSelect('feels')
        ->addSelect('genre')
        ->addSelect('user')
        ->leftJoin('b.translations', 'bookTranslations')
        ->leftJoin('b.bookGenres', 'bookGenres')
        ->leftJoin('b.bookCrews', 'bookCrews')
        ->leftJoin('bookCrews.user', 'user')
        ->leftJoin('bookGenres.genre', 'genre')
        ->leftJoin('b.feels', 'feels')
        ->addSelect('COUNT(bookGenres) AS HIDDEN genreCount')
        ->groupBy('b.id')
    ;

I use symfony serializer for responce data

any ideas?

It is supposed to show you one row by book because of the ->groupBy('b.id') , how many rows do you expect by books?

As for the sorting, you're missing the orderBy:

  ->orderBy('genreCount', 'DESC')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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