Order by a relational count

I think this is best described with an example.




class Book extends \yii\db\ActiveRecord

{

	

}


class Author extends yii\db\ActiveRecord

{

	public function getBooks()

	{

		return $this->hasMany(Book::className(), ['author_id' => 'id']);

	}

	

	public function getBookCount()

	{

		return $this->getBooks()->count();

	}

}


$query = Author::find()

	->orderBy(<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/huh.gif' class='bbc_emoticon' alt='???' />);



As you can see, I want to return the Author models sorted by the number of books. Given the above, how do I create the query using ActiveQuery? I realize this can be done by joining tables, but I am wondering if this can be done using ActiveRecord relations.

In Yii1 this could be done using a STAT relation and with and together, but something similar in Yii2 doesn’t seem to work.

I tried something like this, but the Books relation is not joined with the query. I believe how Yii2 does it is by getting the IDs required and then running a separate query to fulfill the relation.




	$query = Author::find()

		->with('books')

		->orderBy(['COUNT(books.id)' => SORT_DESC]);



Ideally I would like to be able to do something like this:




	$query = Author::find()

		->with('bookCount')

		->orderBy(['bookCount' => SORT_DESC]);






 $query = Author::find()

                ->join('books')

                ->orderBy(['COUNT(books.id)' => SORT_DESC]);



or, if you need the books later on:




 $query = Author::find()

                ->joinWith('books')

                ->orderBy(['COUNT(books.id)' => SORT_DESC]);