A
A
AlexSer2018-08-11 11:54:18
Yii
AlexSer, 2018-08-11 11:54:18

How to count the number of records using ActiveRecord in Yii2?

For example, there is a table Book and Author (Authors). A book, 1 and there can be several openings for 1 book.

Book                    
id|  title|
Autor
id|book_id|name_auth

In addition, in the records, there are books whose authors have not yet been assigned, not added. That is, their id is not present in the Author table. I need to count the number of books that have authors.
$count=Book::find()
            ->leftJoin('Author', '`author`.`book_id` = `book`.`id`')
            ->count();

But this schema outputs the number of entries in the Author field. Only books are needed.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-08-11
@AlexSer

A book, 1 and there can be several openings for 1 book.

What the hell?
1. Why join here?
2.
$books = Book::find()
            ->with('author')
            ->all();
foreach($books as $book){
echo  "количество авторов у книги " . $book->title . ": " . count($book->author);
}

In this case, there should be a relationship with the name getAuthor in the Book model

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question