Type Conversion
Nette Database automatically converts values returned from the database to the corresponding PHP types.
Date and Time
Time values are converted to Nette\Utils\DateTime
objects. If you want time values to be converted to immutable
Nette\Database\DateTime
objects, set the newDateTime
option to true in the configuration.
$row = $database->fetch('SELECT created_at FROM articles');
echo $row->created_at instanceof DateTime; // true
echo $row->created_at->format('j. n. Y');
In the case of MySQL, the TIME
data type is converted to DateInterval
objects.
Boolean Values
Boolean values are automatically converted to true
or false
. For MySQL, TINYINT(1)
is
converted if we set convertBoolean
in the configuration.
$row = $database->fetch('SELECT is_published FROM articles');
echo gettype($row->is_published); // 'boolean'
Numeric Values
Numeric values are converted to int
or float
according to the column type in the database:
$row = $database->fetch('SELECT id, price FROM products');
echo gettype($row->id); // integer
echo gettype($row->price); // float
Custom Normalization
Using the setRowNormalizer(?callable $normalizer)
method, you can set a custom function for transforming rows from
the database. This is useful, for example, for automatic data type conversion.
$database->setRowNormalizer(function(array $row, ResultSet $resultSet): array {
// type conversion happens here
return $row;
});