Answer the question
In order to leave comments, you need to log in
How to display nested lists from linked table?
There are two related tables.
author: id | name
book: id | author_id | title
There is a code that displays a list of authors and the number of books of each of them:
class AuthorController extends Controller {
public function actionIndex() {
$authors = Author::find()->select(['author.id', 'author.name', 'books' => 'count(*)'])
->leftJoin('book', 'author.id = book.author_id')
->groupBy('author.id')->asArray()->all();
return $this->render('index', ['authors' => $authors]);
}
}
<?php foreach($authors as $author){
echo '<h2>'.$author['name'].'</h2>';
echo '<p>Книг: '.$author['books'].'</p>';
}
?>
Answer the question
In order to leave comments, you need to log in
$authors = Author::find()->with('book')->all();
foreach($authors as $author){
echo $author->name;
echo '<br>';
if($author->book){
echo 'у автора ' . count($author->name) . 'книг';
foreach($author->book as $book){
echo $book->title;
echo '<br>';
}
}else{
echo 'этот дядя не писал книг';
echo '<br>';
}
}
Write in the author model, the getBooks method (where do join), and in the controller method select only authors. And in the view in the loop, go through the authors, and in the nested loop, pull the books.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question