I have 2 tables called Books and Reviews. Books table has a one-to-many relationship with Reviews.
I want to search books and sort them by Reviews.
For exam
Use joinWith
. For more see
For example, for your case code like that:
Books::find()
->joinWith(['reviews' => function ($q) {
$q->select(['COUNT(*) as cnt']);
}])
->orderBy(['cnt' => 'DESC'])
->all();
EDIT: I find better solution.
Books::find()
->joinWith(['reviews'])
->select(['*', 'COUNT(reviews.*) as cnt'])
->groupBy('RELATION_FIELD(Example: reviews.book_id)')
->orderBy(['cnt' => 'DESC'])
->all();