Database Explorer
Explorer offers an intuitive and efficient way to work with your database. It automatically handles table relationships and optimizes queries, allowing you to focus on your application logic. It works immediately without configuration. If you need full control over SQL queries, you can use the SQL way.
- Working with data is natural and easy to understand
- Generates optimized SQL queries that fetch only the necessary data
- Provides easy access to related data without the need to write JOIN queries
- Works immediately without any configuration or entity generation
Working with the Explorer begins by calling the table()
method on the Nette\Database\Explorer object (see Connection and Configuration for details on setting up the database
connection):
The method returns a Selection object,
which represents an SQL query. Additional methods can be chained to this object for filtering and sorting results. The query is
assembled and executed only when the data is requested, for example, by iterating with foreach
. Each row is
represented by an ActiveRow object:
Explorer greatly simplifies working with table relationships. The following example shows how easily we can output data from related tables (books and their authors). Notice that no JOIN queries need to be written; Nette generates them for us:
Nette Database Explorer optimizes queries for maximum efficiency. The above example performs only two SELECT queries, regardless of whether we process 10 or 10,000 books.
Additionally, Explorer tracks which columns are used in the code and fetches only those from the database, saving further performance. This behavior is fully automatic and adaptive. If you later modify the code to use additional columns, Explorer automatically adjusts the queries. You don’t need to configure anything or think about which columns will be needed — leave that to Nette.
Filtering and Sorting
The Selection
class provides methods for filtering and sorting data selections.
where($condition, ...$params) |
Adds a WHERE condition. Multiple conditions are combined using AND |
whereOr(array $conditions) |
Adds a group of WHERE conditions combined using OR |
wherePrimary($value) |
Adds a WHERE condition based on the primary key |
order($columns, ...$params) |
Sets sorting with ORDER BY |
select($columns, ...$params) |
Specifies which columns to fetch |
limit($limit, $offset = null) |
Limits the number of rows (LIMIT) and optionally sets OFFSET |
page($page, $itemsPerPage, &$total = null) |
Sets pagination |
group($columns, ...$params) |
Groups rows (GROUP BY) |
having($condition, ...$params) |
Adds a HAVING condition for filtering grouped rows |
Methods can be chained (the so-called fluent interface):
$table->where(...)->order(...)->limit(...)
.
In these methods, you can also use special notations for accessing data from related tables.
Escaping and Identifiers
The methods automatically escape parameters and quote identifiers (table and column names), preventing SQL injection. To ensure proper operation, a few rules must be followed:
- Write keywords, function names, procedures, etc., in uppercase.
- Write column and table names in lowercase.
- Always pass strings using parameters.
where(string|array $condition, …$parameters): static
Filters results using WHERE conditions. Its strength lies in intelligently handling various value types and automatically selecting appropriate SQL operators.
Basic usage:
Thanks to automatic detection of suitable operators, you don’t need to handle various special cases — Nette resolves them for you:
The method correctly handles negative conditions and empty arrays:
You can also pass the result of another table query as a parameter, creating a subquery:
Conditions can also be passed as an array, whose items are combined using AND:
In the array, you can use key ⇒ value pairs, and Nette will again automatically choose the correct operators:
In the array, you can combine SQL expressions with placeholders and multiple parameters. This is suitable for complex conditions with precisely defined operators:
Multiple calls to where()
automatically combine conditions using AND.
whereOr(array $parameters): static
Similar to where()
, this adds conditions, but combines them using OR:
More complex expressions can also be used here:
wherePrimary(mixed $key): static
Adds a condition for the table's primary key:
If the table has a composite primary key (e.g., foo_id
, bar_id
), pass it as an array:
order(string $columns, …$parameters): static
Specifies the order in which rows are returned. You can sort by one or more columns, in ascending or descending order, or according to a custom expression:
select(string $columns, …$parameters): static
Specifies the columns to be returned from the database. By default, Nette Database Explorer returns only the columns that are
actually used in the code. Use the select()
method when you need to retrieve specific expressions:
Aliases defined using AS
are then accessible as properties of the ActiveRow
object:
limit(?int $limit, ?int $offset = null): static
Limits the number of returned rows (LIMIT) and optionally allows setting an offset:
For pagination, it is more appropriate to use the page()
method.
page(int $page, int $itemsPerPage, &$numOfPages = null): static
Facilitates pagination of results. It accepts the page number (starting from 1) and the number of items per page. Optionally, you can pass a reference to a variable where the total number of pages will be stored:
group(string $columns, …$parameters): static
Groups rows according to the specified columns (GROUP BY). It is typically used in conjunction with aggregate functions:
having(string $having, …$parameters): static
Sets a condition for filtering grouped rows (HAVING). It can be used in conjunction with the group()
method and
aggregate functions:
Reading Data
For reading data from the database, several useful methods are available:
foreach ($table as $key => $row) |
Iterates through all rows, $key is the primary key value, $row is an ActiveRow object |
$row = $table->get($key) |
Returns a single row by primary key |
$row = $table->fetch() |
Returns the current row and advances the pointer to the next one |
$array = $table->fetchPairs() |
Creates an associative array from the results |
$array = $table->fetchAll() |
Returns all rows as an array |
count($table) |
Returns the number of rows in the Selection object |
The ActiveRow object is read-only. This means you cannot change the values of its properties. This restriction ensures data consistency and prevents unexpected side effects. Data is loaded from the database, and any changes should be made explicitly and in a controlled manner.
foreach
– Iterating Through All Rows
The easiest way to execute a query and retrieve rows is by iterating using a foreach
loop. It automatically
executes the SQL query.
get($key): ?ActiveRow
Executes the SQL query and returns the row by primary key, or null
if it doesn't exist.
fetch(): ?ActiveRow
Returns the current row and advances the internal pointer to the next one. If there are no more rows, it returns
null
.
fetchPairs(string|int|null $key = null, string|int|null $value = null): array
Returns results as an associative array. The first argument specifies the column name to be used as the key in the array, the second argument specifies the column name to be used as the value:
If only the first parameter is provided, the value will be the entire row, i.e., the ActiveRow
object:
In case of duplicate keys, the value from the last row is used. When using null
as the key, the array will be
indexed numerically starting from zero (then no collisions occur):
fetchPairs(Closure $callback): array
Alternatively, you can pass a callback as a parameter, which will return either a single value or a key-value pair for each row.
fetchAll(): array
Returns all rows as an associative array of ActiveRow
objects, where the keys are the primary key values.
count(): int
The count()
method without a parameter returns the number of rows in the Selection
object:
Note: count()
with a parameter performs the COUNT aggregate function in the database, see below.
ActiveRow::toArray(): array
Converts the ActiveRow
object to an associative array, where keys are column names and values are the
corresponding data.
Aggregation
The Selection
class provides methods for easily performing aggregate functions (COUNT, SUM, MIN, MAX,
AVG, etc.).
count($expr) |
Counts the number of rows |
min($expr) |
Returns the minimum value in a column |
max($expr) |
Returns the maximum value in a column |
sum($expr) |
Returns the sum of values in a column |
aggregation($function) |
Allows any aggregation function, such as AVG() or GROUP_CONCAT() |
count(string $expr): int
Executes an SQL query with the COUNT function and returns the result. The method is used to determine how many rows match a certain condition:
Note: count() without a parameter only returns the number of rows in the Selection
object.
min(string $expr) and max(string $expr)
The min()
and max()
methods return the minimum and maximum values in the specified column or
expression:
sum(string $expr): int
Returns the sum of values in the specified column or expression:
aggregation(string $function, ?string $groupFunction = null): mixed
Allows performing any aggregate function.
If we need to aggregate results that already result from some aggregate function and grouping (e.g., SUM(value)
over grouped rows), we specify the aggregate function to be applied to these intermediate results as the second argument:
In this example, we first calculate the total price of products in each category
(SUM(price * stock) AS category_total
) and group the results by category_id
. Then, we use
aggregation('SUM(category_total)', 'SUM')
to sum these intermediate totals category_total
. The second
argument 'SUM'
specifies that the SUM function should be applied to the intermediate results.
Insert, Update & Delete
Nette Database Explorer simplifies inserting, updating, and deleting data. All the methods mentioned throw a
Nette\Database\DriverException
in case of an error.
Selection::insert(iterable $data)
Inserts new records into the table.
Inserting a single record:
Pass the new record as an associative array or iterable object (like ArrayHash
used in forms), where keys correspond to column names in the table.
If the table has a defined primary key, the method returns an ActiveRow
object, which is reloaded from the
database to reflect any changes made at the database level (triggers, default column values, auto-increment column calculations).
This ensures data consistency, and the object always contains the current data from the database. If it doesn't have a unique
primary key, it returns the passed data as an array.
Inserting multiple records at once:
The insert()
method allows inserting multiple records using a single SQL query. In this case, it returns the
number of inserted rows.
A Selection
object with a data selection can also be passed as a parameter.
Inserting special values:
We can also pass files, DateTime
objects, or SQL literals as values:
Selection::update(iterable $data): int
Updates rows in the table according to the specified filter. Returns the number of actually modified rows.
Pass the columns to be changed as an associative array or iterable object (like ArrayHash
used in forms), where keys correspond to column names in the table:
To change numeric values, you can use the +=
and -=
operators:
Selection::delete(): int
Deletes rows from the table according to the specified filter. Returns the number of deleted rows.
When calling update()
or delete()
, don't forget to use where()
to
specify the rows to be modified/deleted. If where()
is not used, the operation will be performed on the
entire table!
ActiveRow::update(iterable $data): bool
Updates data in the database row represented by the ActiveRow
object. It accepts an iterable with data to be
updated (keys are column names). To change numeric values, you can use the +=
and -=
operators:
After performing the update, the ActiveRow
is automatically reloaded from the database to reflect any changes made
at the database level (e.g., triggers). The method returns true
only if a real data change occurred.
This method updates only one specific row in the database. For bulk updates of multiple rows, use the Selection::update() method.
ActiveRow::delete(): int
Deletes the row from the database represented by the ActiveRow
object. Returns the number of deleted rows, which
should be 1.
This method deletes only one specific row in the database. For bulk deletion of multiple rows, use the Selection::delete() method.
Relationships Between Tables
In relational databases, data is divided into multiple tables and linked together using foreign keys. Nette Database Explorer provides a revolutionary way to work with these relationships – without writing JOIN queries and without needing to configure or generate anything.
To illustrate working with relationships, we'll use an example book database (find it on GitHub). In the database, we have tables:
author
– writers and translators (columnsid
,name
,web
,born
)book
– books (columnsid
,author_id
,translator_id
,title
,sequel_id
)tag
– tags (columnsid
,name
)book_tag
– junction table between books and tags (columnsbook_id
,tag_id
)

Database structure used in examples
In our example book database, we find several types of relationships (although the model is simplified compared to reality):
- One-to-many (1:N) – Each book has one author; an author can write multiple books.
- Zero-to-many (0:N) – A book can have a translator; a translator can translate multiple books.
- Zero-to-one (0:1) – A book can have a sequel.
- Many-to-many (M:N) – A book can have several tags, and a tag can be assigned to several books.
In these relationships, there is always a parent table and a child table. For example, in the relationship
between authors and books, the author
table is the parent, and the book
table is the child – you can
think of it as a book always „belonging“ to an author. This is also reflected in the database structure: the child table
book
contains the foreign key author_id
, which references the parent table author
.
If we need to list books including their authors' names, we have two options. Either retrieve the data with a single SQL query using JOIN:
Or retrieve the data in two steps – first the books, then their authors – and then assemble them in PHP:
The second approach is actually more efficient, although it might be surprising. Data is fetched only once and can be better utilized in the cache. This is precisely how Nette Database Explorer works – it handles everything under the hood and offers you an elegant API:
Accessing the Parent Table
Accessing the parent table is straightforward. These are relationships like a book has an author or a book may
have a translator. The related record is obtained via a property of the ActiveRow object – its name corresponds to the
name of the foreign key column without the _id
suffix:
When accessing the $book->author
property, Explorer looks in the book
table for a column whose
name contains the string author
(i.e., author_id
). Based on the value in this column, it loads the
corresponding record from the author
table and returns it as an ActiveRow
. Similarly,
$book->translator
uses the translator_id
column. Since the translator_id
column can
contain null
, we use the nullsafe operator ?->
in the code.
An alternative approach is offered by the ref()
method, which accepts two arguments: the name of the target table
and the name of the joining column, and returns an ActiveRow
instance or null
:
The ref()
method is useful if property-based access cannot be used, for example, because the table contains a
column with the same name (i.e., author
). In other cases, using property-based access is recommended for better
readability.
Explorer automatically optimizes database queries. When iterating through books in a loop and accessing their related records (authors, translators), Explorer does not generate a query for each book separately. Instead, it performs only one SELECT query for each type of relationship, significantly reducing the database load. For example:
This code executes only these three lightning-fast queries to the database:
The logic for finding the joining column is determined by the implementation of Conventions. We recommend using DiscoveredConventions, which analyzes foreign keys and allows you to easily work with existing relationships between tables.
Accessing the Child Table
Accessing the child table works in the opposite direction. Now we ask which books did this author write or which
books did this translator translate. For this type of query, we use the related()
method, which returns a
Selection
with related records. Let's look at an example:
The related()
method accepts the join description as a single argument with dot notation or as two separate
arguments:
Explorer can automatically detect the correct joining column based on the name of the parent table. In this case, it joins via
the book.author_id
column because the name of the source table is author
:
If multiple possible connections exist, Explorer will throw an AmbiguousReferenceKeyException.
We can, of course, use the related()
method when iterating through multiple records in a loop, and Explorer will
automatically optimize the queries in this case as well:
This code generates only two lightning-fast SQL queries:
Many-to-Many Relationship
For a many-to-many (M:N) relationship, a junction table (in our case, book_tag
) is needed, containing two
foreign key columns (book_id
, tag_id
). Each of these columns refers to the primary key of one of the
linked tables. To retrieve related data, we first get the records from the junction table using related('book_tag')
and then proceed to the target data:
Explorer again optimizes the SQL queries into an efficient form:
Querying Through Related Tables
In the where()
, select()
, order()
, and group()
methods, you can use special
notations to access columns from other tables. Explorer automatically creates the necessary JOINs.
Dot notation (parent_table.column
) is used for 1:N relationships from the perspective of the
child table:
Colon notation (:child_table.column
) is used for 1:N relationships from the perspective of the
parent table:
In the example above with colon notation (:book.title
), the foreign key column is not specified. Explorer
automatically detects the correct column based on the name of the parent table. In this case, it joins via the
book.author_id
column because the name of the source table is author
. If multiple possible connections
exist, Explorer will throw an AmbiguousReferenceKeyException.
The joining column can be explicitly specified in parentheses:
Notations can be chained to access data across multiple tables:
Extending Conditions for JOIN
The joinWhere()
method extends the conditions specified when joining tables in SQL after the ON
keyword.
Let's say we want to find books translated by a specific translator:
In the joinWhere()
condition, you can use the same constructs as in the where()
method –
operators, placeholders, arrays of values, or SQL expressions.
For more complex queries with multiple JOINs, you can define table aliases:
Note that while the where()
method adds conditions to the WHERE
clause, the joinWhere()
method extends the conditions in the ON
clause when joining tables.