P
P
Pios882018-07-06 18:04:10
Yii
Pios88, 2018-07-06 18:04:10

How to output the number of rows from the associated hasMany model in Yii2?

There are 2 MySQL tables,
author: id | name
book: id | author_id | title | other heresy
Tables are connected via author_id => id
There are respectively related models Book and Author and controllers to them.
Task: display a list of authors with an indication of the number of books of each of them.
I understand that I need to get the id value of each author from Author, for this I declare the $id variable and assign it the appropriate value. You can see it in the code below. But it doesn't work as well as we would like. That is, it doesn't work.
Is it possible to somehow get all the "numbers" of books for all authors in one query and display them?
Or is it some kind of cycle? If I assign a specific value to the $id variable, then it actually counts the number of books from the book table with that author_id value. But here's how to do it for everyone and then withdraw it - it's not clear.

class AuthorController extends Controller {
        
    public function actionIndex() {
        
        $author = Author::find()->all();
        $id = Author::find()->select('id')->all();
        $book = Book::find()->where(['author_id' => $id])->count();

        return $this->render('index', ['author' => $author, 'book' => $book]);    
    }
}

Just in case. All this is output to the view in a loop:
<?php if(!empty($author)); ?>
<?php foreach($author as $author): ?>

        <h3><a href="#"> <?=$author->name?> </a></h3>
        <h3><a href="#"> <?=$book?> </a></h3>
        
<?php endforeach; ?>

Z.Y. Yes, I am an absolute zero in PHP, but it just so happened that this task needs to be solved. Save smart people :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-07-09
@webinar

Why are you posting the same questions?
How to output the number of rows from the associated hasMany model in Yii2?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question