title: How to use JOIN in Yii2 Active Record for relational model?
body: <p>I have 2 tables called Books and Reviews. Books table has a one-to-many relationship with Reviews.</p>
  
  <p>I want to search books and sort them by Reviews. </p>
  
  <p>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.</p>
  
  <p>My SQL query is like following:</p>
  
  <pre><code> Books::find()
     -&gt;where([
       'and', 
       ['like', 'books.bookName', $bookName],
       ['like', 'books.status', 'Enabled'] 
      ])
    -&gt;joinWith(['reviews' =&gt; function ($q){
          $q-&gt;select(['COUNT(*) as cnt']);
      }])
    -&gt;orderBy(['cnt' =&gt; 'DESC'])
    -&gt;all();
  </code></pre>
  
  <p>It's giving me following error message:</p>
  
  <blockquote>
    <p>SQLSTATE[42S22]: Column not found: 1054 Unknown column 'cnt' in 'order clause'</p>
  </blockquote>
  
  <p>What am I missing here?</p>