---
title: "Generating Models"
description: "Generate the models of an MVC project from the tables of the database with make:model."
version: "1.0"
---

> Documentation Index
> Fetch the complete documentation index at: https://crest.phalcon.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Generating Models

**MVC** For MVC projects (see the flavor table in [Overview](/1.0/introduction)).

In an MVC project, `make:model` reads a table from the database of the project, and writes a model and a base class. The model extends the base (see [Generated bases](/1.0/controllers#generated-bases)). Crest writes relations only from FOREIGN KEY constraints (see [Relations](#relations)):

```bash
crest make:model users
```

```text
Created src/Models/Base/UsersBase.php
No relations for users: the table has no foreign keys, and no foreign keys point to it. Relations come only from foreign keys.
Created src/Models/Users.php
```

Crest reads the table through the `db` service of your project. Thus it starts your front controller: `crest.php` must name it in `bootstrap` (see [Commands that boot the project](/1.0/booting)). A project from `crest new --flavor=mvc` with a database has the `db` service (see [The database](/1.0/creating-a-project#the-database)). For a project without one, add a provider that registers it (`crest make:provider Db`).

A model finds rows with PHQL. The extension (Phalcon v5) has PHQL, and the `phalcon/phalcon` package (Phalcon v6) requires `phalcon/phql`, the package for PHQL. Thus a model needs no other package.

`Users` extends `UsersBase`, which extends `Phalcon\Mvc\Model`. The base has a property for each column, in the order of the table, and an `initialize()` that sets the table:

```php
public ?int $id = null;
public ?string $name = null;
```

| Column type | Property type |
|---|---|
| the integer types | `?int` |
| `FLOAT`, `REAL`, `DOUBLE` | `?float` |
| `BOOLEAN` on PostgreSQL | `?bool` |
| all others, also `DECIMAL`, the dates and text | `?string` |

The column type is the type that Phalcon reads from the database. MySQL and MariaDB keep a `BOOLEAN` column as `TINYINT(1)`, so it gives `?int`. On SQLite, Phalcon reads `DOUBLE` and `BOOLEAN` columns as `VARCHAR`, so they give `?string`.

On SQLite, a `TINYINT(1)` column gives `?int` before cphalcon 5.24.0 and before `phalcon/phalcon` 6.0.0. From these versions, it gives `?bool`, and a `Select` field in a scaffold.

Each property is nullable, with the default `null`, because a new model has no values yet. The class name comes from the table name: Crest makes the first letter of each part between `_` uppercase. `user_profiles` gives `UserProfiles`. To give a table another class, or a column another property name, see [Names](#names).

When the table changes, run `make:model` again. Crest writes the base again, and keeps your model:

```text
Updated src/Models/Base/UsersBase.php
No relations for users: the table has no foreign keys, and no foreign keys point to it. Relations come only from foreign keys.
Kept src/Models/Users.php: it exists; pass --force to replace it
```

The rules of [Generated bases](/1.0/controllers#generated-bases) apply to the base of a model too. Do not edit it. You can change only the aliases of its relations (in the `RelationAlias` attributes, see [Relations](#relations)) and the names in its `PropertyName` attributes (see [Names](#names)). `--force` replaces the model, but never a base without the `Generated by crest.` line. If you add `initialize()` to your model, call `parent::initialize()` first.

For the errors that stop `make:model` before it writes a file, see [When `make:model` stops](#when-makemodel-stops).

`make:model` is for MVC projects. An ADR project uses repositories, not Active Record models, so the command stops there.

To write the models into a module, add `--module` (see [Generating modules](/1.0/modules)):

```bash
crest make:model users --module=admin
```

```text
Created src/Modules/Admin/Models/Base/UsersBase.php
No relations for users: the table has no foreign keys, and no foreign keys point to it. Relations come only from foreign keys.
Created src/Modules/Admin/Models/Users.php
```

The models and their bases go into the `Models` folder of the module, in its namespace (`App\Modules\Admin\Models`). `--module` works with one table and with `--all` (see [All the tables](#all-the-tables)). A relation names a model in the same module, so write the related tables into the same module. The lines that tell you to run `make:model` again name the option, for example `Run make:model --module=admin for customers too: ...`. Crest reads the tables through the `db` service of the project, also when the module sets its own `db`.

## Names

Crest gives each model the class of its table name, and each property the name of its column. Two settings in `crest.php` and one option change the names:

```php
return [
    'flavor'    => 'mvc',
    'bootstrap' => App\AppFront::class,
    'models'    => [
        'classes'   => ['users' => 'User', 'user-profiles' => 'UserProfile'],
        'camelCase' => true,
    ],
];
```

The `models` key has two more settings, `getSet` and `schema`, which do not change the names (see [Getters and setters](#getters-and-setters) and [The schema](#the-schema)).

In an MVC project, `crest config:show` shows the key (see [Configuration](/1.0/configuration)): the rows `camelCase`, `getSet` and `schema`, each with its origin, and a table with each line of `classes`, sorted by table:

```text
ITEM       VALUE          ORIGIN
...
service    app            default
camelCase  true           declared
getSet     false          default
schema     none           default

PATH        LOCATION                   ORIGIN
...

TABLE          CLASS
user-profiles  UserProfile
users          User
```

When the key is not correct, `config:show` shows the error in a `models` row and exits with 0, and `make:model` stops on it:

```text
service    app                                                default
models     crest.php: models.camelCase must be true or false  declared
```

**Classes.** `classes` gives a class to a table. Write a line only for each table whose class you want to change: the other tables keep the class of their name. Crest does not make a singular class name: `users` gives `Users`, not `User`. For `User`, write the line `'users' => 'User'`. The table name must be exact, with the same case. A line also gives a class to a table whose name gives none (`user-profiles`), or gives a name that PHP reserves (`list`), also with `--all`. With `--all`, a line for a table that the database does not have gives a note:

```text
Note: models.classes names the table Users, which the database does not have; did you mean users?
```

When you add a line for a table that has a model, Crest writes a new base and a new model (`UserBase.php`, `User.php`), and keeps the old files. A note names the old files, and the tables that have relations with the table:

```text
Note: the old files of users stay: src/Models/Users.php and src/Models/Base/UsersBase.php; move your code to User, delete them, then run make:model for invoices
```

Move your code to the new model, delete the old files, and run `make:model` for the tables of the note. Crest prints the note on each run until you delete the old files. With `--all`, the note names only the related tables that the run does not write, such as the tables of `--exclude` (see [All the tables](#all-the-tables)). The note also names a related table that has no model yet: `make:model` then writes a model for it. The new base does not get the `PropertyName` attributes of the old base: give the names again with `--property` (see **One property** below).

Crest prints no note when the old base does not have the `Generated by crest.` line. Crest also prints no note when another table gets the old class (for example, with the line `'members' => 'Users'`), because the old base can be the base of that table.

**camelCase.** With `'camelCase' => true`, each property gets the camelCase form of its column: Crest splits the column at each `_`, makes the first letter of each part uppercase, and then makes the first letter of the name lowercase. `first_name` gives `firstName`, and `name` stays `name`. The other letters do not change, so a column in capitals gives an unusual name (`USER_ID` gives `uSERID`): give it a name with `--property`. The setting applies to each table, on each run.

> **Warning:** When you change `camelCase` in a project that has models, the
> next run of `make:model` renames the properties of each base that it writes,
> and the code that uses the old names stops working. Crest prints a `Renamed`
> line for each property that changes.

**One property.** `--property` gives a name to a column of one table:

```bash
crest make:model users --property="first name=firstName,last_name=lastName"
```

Separate the columns with commas, and give all the names to one `--property`: if you give it two times, Crest uses only the last one. A column whose name has a comma, or a space at the start or the end, cannot get a name. `--property` works only for one table, not with `--all`.

Crest keeps each name of `--property` in a `PropertyName` attribute on the base:

```php
#[\Crest\Attribute\PropertyName('first name', name: 'firstName')]
abstract class UsersBase extends Model
```

On the next runs, you do not give `--property` again: Crest reads the attribute. You can change the name in the attribute, and Crest uses it on the next run. To use the name of `camelCase`, or the column name, again, delete the attribute line and run `make:model` again. When the table no longer has the column, Crest drops the attribute:

```text
Dropped the property name firstName of column 'first name': the table has no such column
```

Crest reads the `PropertyName` attributes as it reads the `RelationAlias` attributes (see [Relations](#relations)). Crest stops, and writes no file, when a `PropertyName` attribute does not have two plain strings (the column and the name), when two attributes have the same column, or when the name in an attribute is not a usable property name. The message names the file and the line.

The order of the names: `--property`, then the attribute, then `camelCase`, then the column name.

**columnMap().** When a property does not have the name of its column, the base gets a `columnMap()` with each column and its property. Phalcon uses it to read and write the rows, but only when the setting `orm.column_renaming` is on, as it is by default. The relations use the property names of the two tables: with `camelCase`, the `belongsTo()` of `invoices` has `'customerId'` (see [Relations](#relations)).

**When a name changes.** When a property gets another name (a change of `camelCase`, a new `--property`, or a changed attribute), Crest prints a line for it. When a relation of another table uses the property, Crest names that table:

```text
Updated src/Models/Base/InvoicesBase.php
Renamed $customer_id to $customerId: change the code that uses it
Run make:model for customers too: its relations use the property names of invoices
Kept src/Models/Invoices.php: it exists; pass --force to replace it
```

With `--all`, Crest reads all the tables in the same run, and writes again each base that changes. Thus it names only the tables of `--exclude` (see [All the tables](#all-the-tables)). It does not name a table that fails later. The summary lists each table that failed: run `make:model` for it again after the fix.

**Published stubs.** `model-base` has the placeholder `{{ columnMap }}`, and the fragment stub `fragment-model-property` (see [Project stubs](/1.0/stubs#project-stubs)) has `{{ property }}`. A copy that you published before Crest added these placeholders does not have them. When a base needs a `columnMap()`, Crest stops:

```text
crest: the published stub /path/to/resources/stubs/mvc/model-base.stub has no {{ columnMap }}; publish it again with crest stub:publish model-base --force, and make your changes in it again
```

Crest writes the `columnMap()` with the stub `fragment-model-column-map`, which has the placeholder `{{ pairs }}`. On the next run, Crest reads the old property names from this `columnMap()`. It reads only the form that it writes: a body with only `return [...];`, and a plain string on each side of each `=>`. When the base has another form (a published `fragment-model-column-map`, or a change by hand), Crest still writes the base, but it cannot find the renamed properties. It prints no `Renamed` line, and prints:

```text
Note: crest cannot read columnMap() of src/Models/Base/CustomersBase.php, so it cannot list the renamed properties
```

Then find the code that uses the properties of that table yourself.

## All the tables

`make:model --all` writes a model and its base for each table of the database, in the order of the table names. For each table, Crest prints a `Table` line, then the lines of `make:model <table>`. At the end, Crest prints a summary:

```bash
crest make:model --all
```

```text
Table customers
Created src/Models/Base/CustomersBase.php
Created src/Models/Customers.php

Table invoices
Created src/Models/Base/InvoicesBase.php
Created src/Models/Invoices.php

2 tables: 2 models created, 0 kept, 0 failed.
```

Each table works as with `make:model <table>`. On another run, Crest compares each base with the base that it makes from the table. If they are not the same, Crest writes the base again. Crest keeps the models, and `--force` replaces them. When the database has no tables to write, Crest prints `No tables to write.`, and the exit status is 0.

With `models.schema`, `--all` writes the tables of that schema (see [The schema](#the-schema)), and the line names the schema:

```text
No tables to write in the schema 'billing'.
```

PostgreSQL gives no tables for a schema that does not exist, so a schema name with a typo gives this line. On MySQL and MariaDB, a schema that does not exist stops Crest:

```text
crest: the schema 'billing' cannot be read: SQLSTATE[42000]: Syntax error or access violation: 1049 Unknown database 'billing'
```

`--all` writes no models for views, and no models for the internal tables of SQLite (for example, `sqlite_sequence`). For the views too, add `--views`:

```bash
crest make:model --all --views
```

For one view, run `make:model <view>`. This works on each database. A view has no keys, so its model has no relations.

Before cphalcon 5.24.0 and before `phalcon/phalcon` 6.0.0, `--all` also writes a model for each sequence on MariaDB. On PostgreSQL, it writes a model for each partition of a partitioned table, and one for the table. Phalcon lists them as tables. From these versions, a partitioned table gives one model, and a sequence or a partition gives none.

To skip tables, give their names to one `--exclude`, separated by commas:

```bash
crest make:model --all --exclude=audit_log,phalcon_migrations
```

Give all the names to one `--exclude`. If you give `--exclude` two times, Crest uses only the last one.

Each name must be the exact name of a table, with the same case. A name that the database does not have stops Crest before it writes a file. When the name differs from a table only in case, the error gives the name of the table:

```text
crest: --exclude: the database has no table Users; did you mean users?
```

For the name of a view (with no `--views`) or an internal SQLite table, Crest prints a note, and continues. A skipped table still gives its relations: with `--exclude=invoices`, the base of `customers` has its `hasMany()` to `Invoices`.

With `--all`, an error of the list in [When `make:model` stops](#when-makemodel-stops) that is about one table makes only that table fail. For example:

- its name gives no class name (`user-profiles`) or a name that PHP reserves (`list`), and no line of `models.classes` gives it a class;
- a column is not a property name and has no name from an attribute;
- Crest cannot use its base;
- a published stub has no placeholder that its base needs.

A table also fails when it gives the same class as another table, also with a different case (`UserProfiles` and `user_profiles`, or `USERS` and `users`): Crest writes none of these tables. Crest prints the reason, and continues with the next table. At the end, Crest lists the tables that failed, so that you can write their models yourself:

```text
Table user-profiles
Failed: 'user-profiles' gives no usable class name; expected a table name like 'users' or 'user_profiles'

Table users
Created src/Models/Base/UsersBase.php
No relations for users: the table has no foreign keys, and no foreign keys point to it. Relations come only from foreign keys.
Created src/Models/Users.php

2 tables: 1 model created, 0 kept, 1 failed.
Failed tables:
  user-profiles: 'user-profiles' gives no usable class name; expected a table name like 'users' or 'user_profiles'
```

The exit status is 1 when a table fails, and 0 when Crest writes or keeps each table. Crest prints all these lines to stdout, also the `Failed` lines, so a log of the output (`> log.txt`) has them in order. An error that is not about one table stops Crest, and goes to stderr: for example, no `db` service, a connection that breaks, or a stub that Crest cannot render. The files of the tables before the error stay, and the next run continues from them.

## Relations

Crest writes relations only from FOREIGN KEY constraints. It does not read the names of the columns: a column `customer_id` with no FOREIGN KEY constraint gives no relation. MySQL tables with the MyISAM engine do not keep foreign keys, so they give no relations. When a table has no foreign keys, and no foreign key of another table points to it, `make:model` prints:

```text
No relations for users: the table has no foreign keys, and no foreign keys point to it. Relations come only from foreign keys.
```

With no foreign keys, write the relations in your model, in `initialize()` after `parent::initialize()`. The `alias` option is the name that you use to read the relation (see the aliases below). For example:

```php
public function initialize(): void
{
    parent::initialize();

    $this->belongsTo(
        'customer_id',
        Customers::class,
        'id',
        ['alias' => 'Customer']
    );
}
```

With foreign keys, the base gets a `belongsTo()` for each foreign key of the table, and a `hasMany()` for each foreign key of another table that points to the table. With these tables:

```sql
CREATE TABLE customers (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(50) NOT NULL);
CREATE TABLE invoices (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    customer_id INTEGER NOT NULL REFERENCES customers(id),
    total DECIMAL(10,2)
);
```

the base of `invoices` gets:

```php
$this->belongsTo(
    'customer_id',
    \App\Models\Customers::class,
    'id',
    ['alias' => 'Customer']
);
```

and the base of `customers` gets:

```php
$this->hasMany(
    'id',
    \App\Models\Invoices::class,
    'customer_id',
    ['alias' => 'Invoices']
);
```

Read a relation through its alias: `$invoice->Customer`, `$customer->Invoices`, or `$invoice->getRelated('Customer')`. The related class is in the folder of your models, also when you did not generate its model yet. Run `make:model` for each table.

The aliases:

- A `belongsTo()` uses the key column without `_id`: `customer_id` gives `Customer`. If the column does not end in `_id`, if the part before `_id` gives no valid name (`_2nd_id`), or if the key has more than one column, the alias comes from the name of the related table: `customers` gives `Customers`.
- A `hasMany()` uses the class of the other table (`Invoices`). If that table has more than one key to this table, the alias adds `By` and the alias of the key: a table `messages` with `sender_id` and `recipient_id` gives `MessagesBySender` and `MessagesByRecipient`.

Each relation has a `RelationAlias` attribute on the base, with the key of the relation and its alias:

```php
/**
 * Generated by crest. Do not edit this file: crest writes it again when you
 * run make:model invoices. Put your code into the model that extends it.
 *
 * You can change the alias in a RelationAlias attribute: crest keeps it when
 * it writes this file again.
 */
#[\Crest\Attribute\RelationAlias('belongsTo invoices(customer_id) -> customers(id)', alias: 'Customer')]
abstract class InvoicesBase extends Model
```

To change an alias, change the `alias:` argument, and run `make:model` for the table again. Crest writes the base with your alias, and keeps it on each later run. An alias in an attribute does not change when another key to the same table comes, or when a later version of Crest has other rules. Change only the `alias:` argument: Crest writes the rest of the base again. If you delete the base, the aliases go back to the rules above.

When the next base has no relation for the key of an attribute, Crest drops the attribute and prints one line for it, so that you know that the alias is gone. This happens when a key column gets a new name, when the key gets another target, or when the table name has another case on another server:

```text
Dropped the alias Buyer of 'belongsTo invoices(buyer_id) -> customers(id)': the database has no such key
```

Crest reads the attributes with the PHP tokenizer, so a formatter can change their layout: line breaks, comments, quotes, named arguments, or a `use` import of `Crest\Attribute\RelationAlias`. Each argument must be a plain string: in single quotes, or in double quotes with no backslash. A constant, or two strings joined with `.`, is not a plain string. The attribute class does not need to exist when your application runs, so an install without Crest (`composer install --no-dev`) works.

Crest stops, and writes no file, when the base is not valid PHP, when a `RelationAlias` attribute does not have two plain strings (the key and the alias), when an alias is not a valid name, when two attributes have the same key, when an alias of an attribute has the name of a property of the table or, with `models.getSet`, the name of a getter (see [Getters and setters](#getters-and-setters)), or when two aliases of attributes are the same (Crest ignores the case). The message names the file and the line.

When another table gets a new key to a table, run `make:model` again for the table that the key points to, so that its base gets the new `hasMany()`. Or run `make:model --all`: Crest compares the base of each table with the base that it makes from the table, and writes the base again if they are not the same.

Crest skips a relation that it cannot write, and prints one line for it:

```text
Skipped the relation belongsTo invoices(customer_id) -> customers(id): the alias Customer has the name of a property
```

Crest skips a relation when:

- the key does not name the referenced columns (SQLite accepts `REFERENCES customers`), before cphalcon 5.24.1 and before `phalcon/phalcon` 6.0.0. From these versions, Phalcon gives the primary key of the referenced table, and Crest writes the relation;
- the related table gives no class name, or a name that PHP reserves;
- Crest cannot read the base of the related table, for example because an attribute in it does not have two plain strings. The line gives the error;
- a key column of the related table has no usable property name, and no `--property` or attribute gives it one (see [Names](#names));
- the alias has the name of a property of the table or, with `models.getSet`, the name of a getter (Crest ignores the case);
- two or more relations have the same alias (Crest ignores the case). Crest skips all of them, but not a relation whose alias comes from an attribute;
- the key points to a table of another schema: the reason is `the table customers is in another schema` (see [The schema](#the-schema)).

Crest writes the other relations. When the reason is the alias (the name of a property or of a getter, or two relations with the same alias), you can give the skipped relation an alias: add an attribute with the key from the line, and run `make:model` again:

```php
#[\Crest\Attribute\RelationAlias('belongsTo invoices(customer_id) -> customers(id)', alias: 'Client')]
```

For the other reasons, an attribute does nothing: Crest drops it, with a `Dropped` line.

When Crest cannot read the base of the related table, correct that base as the line says, and run `make:model` again. When a key column of the related table has no usable property name, give it a name in a run for the related table, and then run `make:model` for this table again:

```text
Skipped the relation hasMany notes(it's_id) -> users(id): column 'it's_id' of table 'notes' has no usable property name
```

```bash
crest make:model notes --property="it's_id=userId"
crest make:model users
```

You can also add a skipped relation in your model, in `initialize()` after `parent::initialize()`.

Composite keys work on MySQL and MariaDB: the fields are arrays, for example `['order_id', 'line_no']`. On PostgreSQL, composite keys work from the C extension cphalcon 5.24.0, and on SQLite from cphalcon 5.24.1. With `phalcon/phalcon`, they work from 6.0.0 on both. Before these versions, Phalcon gives the wrong columns for a composite key on PostgreSQL. On SQLite, Phalcon gives one key for each column of a composite key. Thus Crest writes one relation for each column, and each relation uses only a part of the key.

An alias with the name of a `get` method of `Phalcon\Mvc\Model`, for example `Messages` (`getMessages()`) or `Source` (`getSource()`), works as a property (`$user->Messages`) and through `getRelated('Messages')`, but not as `$user->getMessages()`: PHP calls the method of the model.

## The schema

Crest reads the tables of the default schema of the connection. To read the tables of another schema, give its name in the `models` key of `crest.php`:

```php
'models' => [
    'schema' => 'billing',
],
```

Then `make:model`, `make:model --all` and `make:scaffold` read the tables, the columns and the foreign keys of that schema, and each base calls `setSchema()` after `setSource()`. Thus the model reads and writes the rows of `billing.invoices`:

```php
public function initialize(): void
{
    $this->setSource('invoices');
    $this->setSchema('billing');
}
```

The value must be a string that is not empty and not only white space, or a list of such names (see **More than one schema** below). Crest uses it as you write it: on PostgreSQL, write the name with the case that the server keeps. A `null` value is the same as no value. The schema applies to all the tables of the project, also with `--module`. `config:show` shows it in the `schema` row, with the names of a list separated by commas (see [Names](#names)).

When you change the value, the next run reads the tables of the new schema, and writes the base of each table of the run with the new value. A table that the new schema does not have stops `make:model`:

```text
crest: table 'invoices' was not found in the schema 'billing' of the 'db' service
```

Crest deletes no file. When you remove the key, the next run writes each base with no `setSchema()`.

A model keeps its schema until Crest writes its base again. Thus after you add, change or remove the key, run `make:model --all`: a related model whose base Crest did not write again reads the old schema, with no error.

SQLite has no schemas. When the `db` service is SQLite, and `models.schema` has a value, Crest stops:

```text
crest: crest.php: models.schema is 'billing', but SQLite has no schemas; remove the key
```

When `models.schema` has a value, a published `model-base` must have the placeholder `{{ schema }}`. A copy that you published before Crest added this placeholder does not have it, and Crest stops with the message of **Published stubs** in [Names](#names). With no `models.schema`, a published copy works as before.

**More than one schema.** When the tables of the project are in more than one schema, give a list of schemas:

```php
'models' => [
    'schema' => ['public', 'billing'],
],
```

The first schema is the default schema. `make:model --all` writes a model for each table of each schema, and each base calls `setSchema()` with the schema of its table. A name with no schema is a table of the default schema, and a table of another schema is `<schema>.<table>`. This applies to each name: the table of `make:model` and `make:scaffold`, the names of `--exclude`, the keys of `models.classes`, and the keys of the `RelationAlias` attributes:

```bash
crest make:model invoices                          # public.invoices
crest make:model billing.invoices                  # billing.invoices
crest make:model --all --exclude=billing.audit_log
```

A name with the default schema is the table: `public.invoices` is `invoices`. This is also true for a string, for example `billing.invoices` with `'schema' => 'billing'`.

`--all` prints the name of each table, for example `Table billing.invoices`, and the comment of each base gives the command for its table, for example `run make:model billing.invoices`.

A name can be in the list one time only, without regard to case. In a command and in `--exclude`, a name with a schema that the list does not have stops Crest before it reads the database:

```text
crest: the schema 'crm' of 'crm.customers' is not in models.schema
```

A `models.classes` key for such a schema gives a note with `--all`, as a key for a table that the database does not have. Two `models.classes` keys for one table, for example `users` and `public.users`, stop Crest.

A name with no schema that the default schema does not have stops `make:model`. When other schemas of the list have the table, the error gives their names:

```text
crest: table 'invoices' was not found in the schema 'public' of the 'db' service; did you mean billing.invoices?
```

The class of a table of another schema comes from the table, with no schema: `billing.invoices` gives `Invoices`. When two tables give one class, the table of the default schema keeps it, and the other table fails until `models.classes` gives it a class:

```text
Failed: the tables billing.users and users give the class Users; add 'billing.users' to models.classes
```

```php
'models' => [
    'schema'  => ['public', 'billing'],
    'classes' => ['billing.users' => 'BillingUser'],
],
```

When neither table is in the default schema, the error gives both names, and a line for one of them is enough. A table with a line in `models.classes` keeps its class, as the table of the default schema does: the error then gives only the other table. `make:model billing.users` stops with the same error.

A foreign key to a table of a schema of the list gives a relation in each direction: a `belongsTo()` in the model of the key, and a `hasMany()` in the model of the referenced table. Crest gets the schema of the referenced table from Phalcon (`getReferencedSchema()`). A key to a schema that the list does not have gives a `Skipped` line:

```text
Skipped the relation belongsTo receipts(customer_id) -> crm.customers(id): the schema crm is not in models.schema
```

Before cphalcon 5.24.1, on PostgreSQL, Phalcon gives the name of the database as the schema of each key. Thus with a list of schemas, each key gives a `Skipped` line there, also a key in one schema. cphalcon 5.24.1 and `phalcon/phalcon` 6.0.0 have the fix. A string, or no key, reads the keys as before, on each version.

`model-base` has the placeholder `{{ name }}`: the name of the table, with its schema when it is not the default schema, for the comment of the base. `{{ table }}` is the table with no schema, for `setSource()`. A copy that you published before Crest added `{{ name }}` works, and its comment gives the table with no schema.

**A key to another schema.** With a string, or with no key, Crest writes a relation only to a table of the schema that it reads. A foreign key to a table of another schema gives no relation, also with no `models.schema`:

```text
Skipped the relation belongsTo invoices(customer_id) -> customers(id): the table customers is in another schema
```

Crest finds such a key from the list of the tables: the referenced table is not a table of the schema. A base from an older version of Crest can have a relation like that. The next run removes it, and the code that uses its alias stops working. A `RelationAlias` attribute for the key gets a `Dropped` line. If you need the relation, write it in your model.

The limits:

- When the schema also has a table or a view with the name of the referenced table, Crest cannot see the difference. It writes the relation to the model of that table or view in the schema.
- A key from a table of another schema to a table of this schema gives no `hasMany()`: Crest does not read the other schemas. With a list of schemas, Crest reads each schema of the list (see **More than one schema**).
- On PostgreSQL, two schemas can have the same table with the same key column. If you do not give the keys a name, PostgreSQL gives the two keys the same name, for example `invoices_customer_id_fkey`. Two keys with the same name can point to tables or columns with different names. For such keys, before cphalcon 5.24.0 and before `phalcon/phalcon` 6.0.0, Phalcon gives one key with the columns of the two keys. Crest then writes a relation with the column two times, or a `Skipped` line, for that key. To fix it, give one of the two keys another name, or use the release with the fix.

## Getters and setters

phalcon-devtools is the Phalcon Devtools command line tool (see [References](/1.0/introduction#references)). With `--get-set`, it wrote models with protected properties, and a getter and a setter for each column. With `'getSet' => true` in the `models` key of `crest.php`, each base that `make:model` writes has protected typed properties, and a getter and a setter for each property. The base of the table `people` (`id`, `first_name`) is:

```php
abstract class PeopleBase extends Model
{
    protected ?int $id = null;
    protected ?string $first_name = null;

    public function initialize(): void
    {
        $this->setSource('people');
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function setId(?int $value): static
    {
        $this->id = $value;

        return $this;
    }

    public function getFirstName(): ?string
    {
        return $this->first_name;
    }

    public function setFirstName(?string $value): static
    {
        $this->first_name = $value;

        return $this;
    }
}
```

The default is `false`, and a `null` value counts as no value. A value that is not `true` or `false` stops `make:model` and `make:scaffold`. The setting applies to each table of the project.

**The names.** The methods are `get<Name>()` and `set<Name>()`. Crest makes `<Name>` from the property: it splits the property at each `_`, and makes the first letter of each part uppercase. `first_name` gives `getFirstName()`. With `camelCase`, `firstName` also gives `getFirstName()`, so a change of `camelCase` does not change the methods. `--property=first_name=givenName` gives `getGivenName()`. A setter returns the model, so you can chain the setters: `$user->setFirstName('Ann')->setAge(30)`.

Phalcon uses the methods in `toArray()`, in `assign()` (when `disableAssignSetters` is off), in the forms, and for `$user->first_name` from outside the model. `findFirst()` and `save()` do not use the methods: they read and write the protected properties directly. Thus a getter or a setter that you change in your model does not run when Phalcon reads a row or saves it. (When the setting `orm.call_setters_on_hydration` is on, `findFirst()` calls the setters. The setting is off by default.) Two things change for the code outside the model:

- `isset($user->first_name)` is true also when the value is null;
- `get_object_vars()` and `foreach` do not show the columns. `(array)` gives the columns, but not with the key `first_name`: the key of a protected property starts with `"\0*\0"`.

`$user->first_name ?? 'none'` still gives `'none'` for a null value.

**What stops the command.** With the key, these names stop `make:model` before it writes a file. With `--all`, only the table of the name fails.

- The getter or the setter is a method of `Phalcon\Mvc\Model`. For example, the column `source` gives `getSource()`:

  ```text
  crest: column 'source' of table 'pages' gives the method getSource(), which Phalcon\Mvc\Model has; give it another name with --property="source=<name>"
  ```

  A name from `--property` or from a `PropertyName` attribute gives the same error, with its source.
- Two properties give one method name, without regard to case, for example `first_name` and `firstName`.

Phalcon gives the related records of an alias through `get<Alias>()`, and a getter of the base would hide them. Thus Crest skips a relation whose alias is the `<Name>` of a property, without regard to case. For example, the column `billing_address` of `invoices` gives `getBillingAddress()`, the getter of the alias `BillingAddress`:

```text
Skipped the relation belongsTo invoices(billing_address_id) -> addresses(id): the alias BillingAddress has the name of a getter
```

An alias from a `RelationAlias` attribute stops the command, and you change it.

**A change of the key.** When a property gets another name, Crest prints a line for its methods after the `Renamed` line of the property:

```text
Renamed getFname() and setFname() to getGivenName() and setGivenName(): change the code that uses them
```

From `true` to `false`, the base gets public properties and no methods, and Crest prints a line for each property:

```text
Removed getFirstName() and setFirstName(): change the code that uses them
```

From `false` to `true`, Crest prints a line for each base:

```text
Note: the properties of <base file> are protected now; code outside the model goes through the getters and setters
```

**Published stubs.** The getter and the setter come from the stub `fragment-model-get-set`. With the key, `fragment-model-property` needs the placeholder `{{ visibility }}`, and `model-base` needs `{{ methods }}`. A copy that you published before Crest added these placeholders does not have them: publish it again with `crest stub:publish <name> --force`, and make your changes in it again. With no key, an old copy works.

**Moving a devtools `--get-set` model.**

1. Set `'getSet' => true` in the `models` key of `crest.php`. If devtools used `camelize`, also set `'camelCase' => true`.
2. Run `crest make:model --all`. Crest writes each base. A model file that exists stays as it is, because Crest writes a model one time.
3. In each model:
   - change `extends Model` to `extends <Class>Base`, with the `use` line of the `Base` namespace;
   - delete the properties, the getters and the setters that devtools wrote;
   - delete `columnMap()` and the `setSource()` line, because the base has them;
   - keep your own code. If the model keeps `initialize()`, call `parent::initialize()` first.

A property, a getter or a setter of devtools that stays in the model stops PHP when it loads the model, for example:

```text
Fatal error: Declaration of Users::getAge() must be compatible with UsersBase::getAge(): ?int
Fatal error: Type of Users::$age must be ?int (as in class UsersBase)
```

Delete them. To change a getter or a setter, keep the declaration of the base.

The code that calls the methods keeps working: the names are the same, and you can chain the setters. There are two differences:

- A setter accepts only the type of the column, or null. In a file with `strict_types`, another type is a `TypeError`. A write through `__set()` (`$user->age = '42'`) and `assign()` use the weak rules of PHP: `'42'` converts, but `'abc'` for an `int` is a `TypeError`. The setters of devtools had no types, so they accepted each value.
- A getter gives the typed value.

Before `phalcon/phalcon` 6.0.0, a write through `__set()` or `assign()` gives a `TypeError` when the value does not have the type of the column, also for `'42'`.

## When `make:model` stops

Crest stops, and writes no file, when:

- the table name gives no class name (`user-profiles`), or a name that PHP reserves (`list`), and `models.classes` gives it no class (see [Names](#names));
- the project has no `db` service, the service is not a Phalcon database adapter, or it cannot connect;
- the table does not exist (in the schema of `models.schema`, when you set it);
- `models.schema` has a value, and the `db` service is SQLite (see [The schema](#the-schema));
- a column name cannot be a property name, and no `--property` or attribute gives it another name. Examples: `first name` (not a property name) and `container` (a property of `Phalcon\Mvc\Model`). The error gives the `--property` to use (see [Names](#names));
- two columns give the same property name (with `camelCase`, `first_name` and `firstName`): the error tells you to give one of them another name with `--property`;
- the base is not valid PHP, or Crest cannot use a `RelationAlias` or a `PropertyName` attribute in it (see [Relations](#relations) and [Names](#names));
- the `models` key of `crest.php` is not correct, or `--property` names a column that the table does not have (see [Names](#names));
- a published stub has no `{{ columnMap }}` or `{{ property }}`, and the base needs a `columnMap()` (see [Names](#names)), or the published `model-base` has no `{{ schema }}`, and `models.schema` has a value (see [The schema](#the-schema));
- `models.getSet` is `true`, and a getter or a setter is a method of `Phalcon\Mvc\Model`, two properties give one method name, or a published stub has no `{{ visibility }}` or `{{ methods }}` (see [Getters and setters](#getters-and-setters));
- `--module` names a module that does not exist (see [Generating modules](/1.0/modules)).

Source: https://crest.phalcon.io/1.0/models/index.mdx
