How Nette Database Explorer works with relationships
masterThe Nette\Database\Explorer layer optimizes data fetching by avoiding the 'N+1 query problem'. Instead of running a new query for every single row in a loop, it fetches related data in bulk using IN (...) clauses.
When you access a relationship (e.g., $book->author), the Explorer identifies the necessary IDs from the current collection and executes a single query to fetch all related records at once. If caching is enabled (default), it further optimizes by only selecting the specific columns that have been accessed.
// Example of efficient relationship fetching
$books = $explorer->table('book');
foreach ($books as $book) {
// Accessing 1:N relationship (author)
echo $book->author->name;
// Accessing M:N relationship via a junction table
foreach ($book->related('book_tag') as $bookTag) {
echo $bookTag->tag->name;
}
}