On the example of this code:

$books = Books::find() ->joinWith(['reviews']) ->select(['books.id','books.name', 'COUNT(reviews.id) as cnt']) ->groupBy('books.id') ->orderBy('books.name') ->all(); 

How to display (get) id, name and the number of all reviews (cnt)?

  • 'COUNT (DISTINCT (reviews.id)) as cnt' - Vanya Avchyan

1 answer 1

Like a regular query, the $books variable will have an array with Books objects, just to display cnt you need to create a public method:

 class Books extends ActiveRecord { public $cnt; //Дальше ваш класс } 

And then you just get the data:

 foreach ($books as $book) { echo 'Book ID: ' . $book->id . PHP_EOL; echo 'Book name: ' . $book->name . PHP_EOL; echo 'Reviews: ' . $book->cnt . PHP_EOL; } 
  • one
    Thank you so much - RostD