E
E
Evgenii Borovoi2020-09-17 08:15:03
Laravel
Evgenii Borovoi, 2020-09-17 08:15:03

Is it possible to get a collection in which each object contains all child records in one query?

Per the documentation, standard eager loading:

$books = App\Models\Book::with('author')->get();

foreach ($books as $book) {
    echo $book->author->name;
}

And it is possible to get a collection of authors, in which each author has books which contains all the books of this author without foreach, join, etc. and without creating a separate method in Author? Something like
Author::all()->books()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jazzus, 2020-09-17
@EugeneOne77

Author::with('books')->get(); and will get a collection of authors with their books if the hasMany link exists.

E
Evgenii Borovoi, 2020-09-17
@EugeneOne77

Thank you. I just looked at the result with a dump - there seem to be no books there. After the answer, I looked at the calls in the panel - everything works. I did not take into account that Laravel takes into account everything, including foreach in the blade.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question