P
P
Pios882018-07-09 18:19:25
Yii
Pios88, 2018-07-09 18:19:25

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]);   
    }
}

Performance:
<?php foreach($authors as $author){
  echo '<h2>'.$author['name'].'</h2>';
  echo '<p>Книг: '.$author['books'].'</p>';
}
 ?>

I broke my head how to modify the code so that it was possible to display not the number of books, but their list. That is, something like this:
Author 1:
- book 1
- book 2
- book 3
Author 2:
- book 1
- book 2
, etc.
Where "Author N" is the name from the author table, and "book N" are the titles from the book table.
My qualifications for this business are not enough. Tell me how you can modify the above code or how can you do it in some other way?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-07-09
@Pios88

$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>';
         }
}

Naturally, you first need to create a relationship of the hasMany type in the model. If "connections" is a terrible word, you should either
read about connections
or
look at connections

V
Viktor Yanyshev, 2018-07-09
@villiwalla

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 question

Ask a Question

731 491 924 answers to any question