Entity Mapping
**************
.[perex]{data-version:3.3.0}
Would you like the rows of the `product` table to be `ProductRow` objects with your own methods, columns with real PHP types, and `$product->createdAt` instead of `$product->created_at`? That is what entity mapping does, and it takes a few lines of configuration.
Out of the box, [Explorer |explorer] returns every row as a generic [ActiveRow |api:Nette\Database\Table\ActiveRow] object and reads its columns through magic properties, so neither your IDE nor PHPStan knows what a row contains. With entity mapping:
- the rows of each table are objects of your own class,
- columns become typed properties that your IDE and PHPStan understand,
- your PHP code can use camelCase names while the database keeps its snake_case columns.
Your Own Class for the Rows of a Table
======================================
Let's say you want every row of the `product` table to know whether the product is in stock. Tell Explorer in the configuration where your row classes live:
```neon
database:
dsn: ...
mapping:
tables: App\Entity\*Row
```
The asterisk is replaced by the table name in PascalCase: the rows of `product` become `App\Entity\ProductRow` objects, the rows of `order_item` become `App\Entity\OrderItemRow`. A schema prefix such as `public.` is left out. The class is an ordinary subclass of `ActiveRow`:
```php
namespace App\Entity;
use Nette\Database\Table\ActiveRow;
class ProductRow extends ActiveRow
{
public function isInStock(): bool
{
return $this->stock > 0;
}
}
```
Now `$explorer->table('product')->get(1)` returns a `ProductRow` and you can call `$product->isInStock()`. And if a table has no class of its own, such as `order_item` when you never create `OrderItemRow`? Its rows simply stay `ActiveRow` objects, so you write classes only for the tables where you want something extra.
When the tables follow different rules, list them one by one. The asterisk works in the table name as well:
```neon
database:
mapping:
tables:
product: App\Entity\ProductRow
forum_*: App\Forum\*Row # forum_post → App\Forum\PostRow
*: App\Entity\*Row # all other tables
```
An exact table name always wins; the patterns are tried in the order you write them.
Typed Columns
=============
Reading `$product->stock` works, but it is magic: PHP knows nothing about the column, so your IDE does not offer it and PHPStan does not know it is an `int`. PHP 8.4 offers a better way: declare each column as a property whose `get` hook reads the column.
```php
namespace App\Entity;
use Nette\Database\Table\ActiveRow;
enum Status: string
{
case Active = 'active';
case Hidden = 'hidden';
}
class ProductRow extends ActiveRow
{
public string $title { get => $this->column('title'); }
public int $stock { get => $this->column('stock'); }
public ?Status $status { get => $this->enum(Status::class, 'status'); }
}
```
The `column()` method returns the value of the column you name, `enum()` also turns it into a case of the given enum and keeps `null` as `null`. A value that has no case in the enum throws an exception naming the table and the column, so a typo in the data does not slip through.
Notice that the properties are read-only. Writing `$product->title = 'Lamp'` throws an error, because a row is changed by `update()`, never by assigning to it. The reads still go through Explorer, which remembers the columns you used and next time selects only those.
camelCase Properties
====================
Databases usually name columns in snake_case (`created_at`), while PHP code uses camelCase (`createdAt`). Turn on the translation and you no longer have to switch between the two:
```neon
database:
mapping:
tables: App\Entity\*Row
camelCase: true
```
```php
$product = $explorer->table('product')->get(1);
echo $product->createdAt; // reads the column created_at
echo $product->authorId; // reads the column author_id
$product->update([
'createdAt' => new DateTime, // writes the column created_at
]);
$explorer->table('product')
->where('createdAt > ?', $since) // WHERE created_at > ...
->order('createdAt DESC'); // ORDER BY created_at DESC
```
The translation works wherever you work with the columns of a table: in reading rows, in the keys of `toArray()`, in the data of `insert()`, `insertMany()` and `update()`, and in column names inside `where()`, `order()`, `select()`, `group()` and other methods of a selection. The original names such as `created_at` keep working too. Only SQL you write yourself in `$explorer->query()` is not translated; it always uses the names from the database.
In a typed property, the hook names the column as the database knows it:
```php
public DateTimeInterface $createdAt { get => $this->column('created_at'); }
```
The translation needs a schema in snake_case, so that every column turns into a property and back to the same column. Explorer checks this for all tables whenever it reads the database structure, and a column that breaks the rule throws an exception naming it. Typically it is a column with an uppercase letter, or one with an underscore before a digit, such as `address_2`: digits have no uppercase form, so `address2` would translate back to `address2`. Map such columns by hand with `except`:
```neon
database:
mapping:
camelCase: true
except:
address2: address_2 # property: column
```
.[note]
Explorer checks the mapping only when it builds the cache of the database structure. After you change the mapping configuration, clear the cache, just as you do after changing the schema.
Custom Mapping
==============
When the rules above do not fit your project, write your own mapping. It is a class implementing the [api:Nette\Database\EntityMapping] interface:
```php
interface EntityMapping
{
function getClassName(string $table): ?string;
function getPropertyName(string $name): string;
function getColumnName(string $name): string;
}
```
- `getClassName()` returns the row class for a table, or `null` to keep `ActiveRow`.
- `getPropertyName()` translates a column name to a property name and `getColumnName()` does the opposite. To leave names as they are, return the argument unchanged.
Pass your mapping as the fifth argument when you create `Explorer` yourself:
```php
$explorer = new Nette\Database\Explorer(
$connection,
$structure,
$conventions,
$cacheStorage,
new MyEntityMapping,
);
```
{{maintitle: Nette Database Entity Mapping: Row Classes and Typed Columns}}
{{description: Map database tables to your own row classes, give columns native PHP types with property hooks and use camelCase properties on a snake_case schema.}}
Entity Mapping
Would you like the rows of the product table to be ProductRow
objects with your own methods, columns with real PHP types, and $product->createdAt instead of
$product->created_at? That is what entity mapping does, and it takes a few lines of configuration.
Out of the box, Explorer returns every row as a generic ActiveRow object and reads its columns
through magic properties, so neither your IDE nor PHPStan knows what a row contains. With entity mapping:
- the rows of each table are objects of your own class,
- columns become typed properties that your IDE and PHPStan understand,
- your PHP code can use camelCase names while the database keeps its snake_case columns.
Your Own Class for the Rows of a Table
Let's say you want every row of the product table to know whether the product is in stock. Tell Explorer in the
configuration where your row classes live:
database:
dsn: ...
mapping:
tables: App\Entity\*Row
The asterisk is replaced by the table name in PascalCase: the rows of product become
App\Entity\ProductRow objects, the rows of order_item become App\Entity\OrderItemRow. A
schema prefix such as public. is left out. The class is an ordinary subclass of ActiveRow:
namespace App\Entity;
use Nette\Database\Table\ActiveRow;
class ProductRow extends ActiveRow
{
public function isInStock(): bool
{
return $this->stock > 0;
}
}
Now $explorer->table('product')->get(1) returns a ProductRow and you can call
$product->isInStock(). And if a table has no class of its own, such as order_item when you never
create OrderItemRow? Its rows simply stay ActiveRow objects, so you write classes only for the tables
where you want something extra.
When the tables follow different rules, list them one by one. The asterisk works in the table name as well:
database:
mapping:
tables:
product: App\Entity\ProductRow
forum_*: App\Forum\*Row # forum_post → App\Forum\PostRow
*: App\Entity\*Row # all other tables
An exact table name always wins; the patterns are tried in the order you write them.
Typed Columns
Reading $product->stock works, but it is magic: PHP knows nothing about the column, so your IDE does not offer
it and PHPStan does not know it is an int. PHP 8.4 offers a better way: declare each column as a property whose
get hook reads the column.
namespace App\Entity;
use Nette\Database\Table\ActiveRow;
enum Status: string
{
case Active = 'active';
case Hidden = 'hidden';
}
class ProductRow extends ActiveRow
{
public string $title { get => $this->column('title'); }
public int $stock { get => $this->column('stock'); }
public ?Status $status { get => $this->enum(Status::class, 'status'); }
}
The column() method returns the value of the column you name, enum() also turns it into a case of the
given enum and keeps null as null. A value that has no case in the enum throws an exception naming the
table and the column, so a typo in the data does not slip through.
Notice that the properties are read-only. Writing $product->title = 'Lamp' throws an error, because a row is
changed by update(), never by assigning to it. The reads still go through Explorer, which remembers the columns you
used and next time selects only those.
camelCase Properties
Databases usually name columns in snake_case (created_at), while PHP code uses camelCase (createdAt).
Turn on the translation and you no longer have to switch between the two:
database:
mapping:
tables: App\Entity\*Row
camelCase: true
$product = $explorer->table('product')->get(1);
echo $product->createdAt; // reads the column created_at
echo $product->authorId; // reads the column author_id
$product->update([
'createdAt' => new DateTime, // writes the column created_at
]);
$explorer->table('product')
->where('createdAt > ?', $since) // WHERE created_at > ...
->order('createdAt DESC'); // ORDER BY created_at DESC
The translation works wherever you work with the columns of a table: in reading rows, in the keys of toArray(), in
the data of insert(), insertMany() and update(), and in column names inside
where(), order(), select(), group() and other methods of a selection. The
original names such as created_at keep working too. Only SQL you write yourself in $explorer->query()
is not translated; it always uses the names from the database.
In a typed property, the hook names the column as the database knows it:
public DateTimeInterface $createdAt { get => $this->column('created_at'); }
The translation needs a schema in snake_case, so that every column turns into a property and back to the same column. Explorer
checks this for all tables whenever it reads the database structure, and a column that breaks the rule throws an exception naming
it. Typically it is a column with an uppercase letter, or one with an underscore before a digit, such as address_2:
digits have no uppercase form, so address2 would translate back to address2. Map such columns by hand
with except:
database:
mapping:
camelCase: true
except:
address2: address_2 # property: column
Explorer checks the mapping only when it builds the cache of the database structure. After you change the mapping
configuration, clear the cache, just as you do after changing the schema.
Custom Mapping
When the rules above do not fit your project, write your own mapping. It is a class implementing the Nette\Database\EntityMapping interface:
interface EntityMapping
{
function getClassName(string $table): ?string;
function getPropertyName(string $name): string;
function getColumnName(string $name): string;
}
getClassName() returns the row class for a table, or null to keep ActiveRow.
getPropertyName() translates a column name to a property name and getColumnName() does the opposite.
To leave names as they are, return the argument unchanged.
Pass your mapping as the fifth argument when you create Explorer yourself:
$explorer = new Nette\Database\Explorer(
$connection,
$structure,
$conventions,
$cacheStorage,
new MyEntityMapping,
);