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 example, if there are 10 books available and books has review in Reviews then I want to find all books by using WHERE clause and count there reviews and then order all books based on the review number.
My SQL query is like following:
Books::find()
->where([
'and',
['like', 'books.bookName', $bookName],
['like', 'books.status', 'Enabled']
])
->joinWith(['reviews' => function ($q){
$q->select(['COUNT(*) as cnt']);
}])
->orderBy(['cnt' => 'DESC'])
->all();
It's giving me following error message:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cnt' in 'order clause'
What am I missing here?
Use
joinWith
. For more seeFor example, for your case code like that:
EDIT: I find better solution.