Brug joinWith
. For mere se
For eksempel for din sagskode sådan:
Books::find()
->joinWith(['reviews' => function ($q) {
$q->select(['COUNT(*) as cnt']);
}])
->orderBy(['cnt' => 'DESC'])
->all();
EDIT:Jeg finder en bedre løsning.
Books::find()
->joinWith(['reviews'])
->select(['*', 'COUNT(reviews.*) as cnt'])
->groupBy('RELATION_FIELD(Example: reviews.book_id)')
->orderBy(['cnt' => 'DESC'])
->all();