Сорт -отношения модели подсчет YII2
$query = Folder::find()->joinWith(['documents'])->orderBy(['COUNT(documents.id)' => SORT_ASC])->groupBy('folder.id');
Successful Sheep
$query = Folder::find()->joinWith(['documents'])->orderBy(['COUNT(documents.id)' => SORT_ASC])->groupBy('folder.id');