Because your code isn't written in English it is a bit hard for me to understand it, but I advise you to read a bit about the N+1 problem. You can probably remove the second query from the loop in order to cut down your SQL queries. This is called eager loading.
Here is an example:
SELECT * FROM authors // first query
foreach ($authors as $author) {
SELECT * FROM books WHERE author_id = $author->id // second query
}
With 10 authors, this runs just fine. But with 100 authors, you are running 101 queries: 1 to get the list of authors, and then 1 for every author. In other words, more authors means more queries and therefor a longer loading time.
You can speed things up by removing the second query from the foreach-loop:
SELECT * FROM authors // first query
$author_ids = array();
foreach ($authors as $author) {
$author_ids[] = $author->id; // add author id to array
}
$author_ids = implode(',', $author_ids); // create a list of comma-seperated ids
SELECT * FROM books WHERE author_id IN ($author_ids) // second query
foreach ($authors as $author) {
// link books to authors
}
This way you use one query to retrieve all the books, and then you use PHP to link books to the right authors.
It is a bit more complicated, but it reduces the number of SQL queries to 2. This is obviously still very simplistic, but it should give you an idea of the concept.