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?
An ActiveQuery can be a normal query or be used in a relational context. ActiveQuery instances are usually created by yii\db\ActiveRecord::find() and yii\db\ActiveRecord::findBySql(). Relational queries are created by yii\db\ActiveRecord::hasOne() and yii\db\ActiveRecord::hasMany().
Yii Query Builder offers an object-oriented method for building SQL queries, which helps reduce risk of SQL injection attacks. And Yii Active Record (AR), implemented as a widely adopted Object-Relational Mapping (ORM) approach, further simplifies database programming.
Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.
Deleting Data You can call yii\db\ActiveRecord::deleteAll() to delete multiple or all rows of data.
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();
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