Answer the question
In order to leave comments, you need to log in
How to display number of rows from linked table by key value?
There is a table book and author. Linked through the id (author) and author_id (for the book) columns. You need to display the number of books for each author. Here is the code I wrote:
class AuthorController extends Controller {
public function actionIndex() {
$author = Author::find()->all();
$id = Author::find()->select('id');
$book = Book::find()->select(['author_id' => $id])->count();
return $this->render('index', ['author' => $author, 'book' => $book, 'id' => $id]);
}
}
foreach ($book as $author_id) {
$book = Book::find()->select(['author_id' => $author_id])->count();
}
<?php if(!empty($author)); ?>
<?php foreach($author as $author): ?>
<h3><a href="#"> <?=$author->name?> </a></h3>
<h3><a href="#"> <?=$author->id?> </a></h3>
<h3><a href="#"> <?=$book?> </a></h3>
<?php endforeach; ?>
Answer the question
In order to leave comments, you need to log in
Try like this:
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]);
}
}
foreach($authors as $author){
echo '<h2>'.$author['id'].') '.$author['name'].'</h2>'; // 1) Иван И.И.
echo '<p>Книг: '.$author['books'].'</p>'; // Книг: 17
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question