Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JOIN in Yii2 Active Record for relational model?

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?

like image 750
The Coder Avatar asked Apr 04 '15 14:04

The Coder


People also ask

What is active query in Yii2?

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().

What is ORM in Yii2?

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.

Is null in Yii2 query?

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.

How to delete Record in Yii2?

Deleting Data You can call yii\db\ActiveRecord::deleteAll() to delete multiple or all rows of data.


1 Answers

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();
like image 65
vitalik_74 Avatar answered Oct 08 '22 17:10

vitalik_74