Skip to content

Migration Methods

The methods of a migration class: drop a table, the helper methods, custom SQL and the data.

Each migration file is for one table. Its class can have the methods below. The package calls each method that the class has. A method can contain any code.

The package calls the methods for each table, not one time for the run. In each version, it takes the tables in the alphabetical order of the file names, or in the order of --table.

Running to up

For each table of the version, the package calls:

  1. morph(). When morphTable() creates the table, it calls afterCreateTable(). It does not call afterCreateTable() for a table that exists.
  2. up().
  3. afterUp(), only if the class has an up() method.

After all the tables of the version, the package adds the version to the log.

Running to down

For each table of the version that the package removes, it calls:

  1. down() of the version that it removes.
  2. afterDown(), only if the class has a down() method.
  3. morph() of the previous version. If the previous version has no file for the table, the package uses the newest earlier version that has one.

After all the tables of the version, the package removes the version from the log.

Helper methods

The Phalcon\Migrations\Mvc\Model\Migration class has these methods, which you can use in your migration methods:

Method Description
morphTable(string $tableName, array $definition): void Creates the table, or changes the table to match the columns, indexes, references and options in the definition
batchInsert(string $tableName, array $fields, int $size = 1024): void Inserts the rows of the <table>.dat file of the version, in one transaction. It inserts $size rows in each query. With --truncate, it first deletes all the rows of the table
batchDelete(string $tableName): void Deletes all the rows of the table, if the <table>.dat file of the version exists
getConnection(): AdapterInterface Returns the database adapter (Phalcon\Migrations\Db\Adapter\AdapterInterface)

Export data

generate can export the data of a table. It writes the rows to a <table>.dat file (CSV format) in the version directory. The --data option controls how the migration imports the data:

Value Generated code
oncreate afterCreateTable() calls batchInsert(). The data is imported only when the table is created
always up() calls batchInsert() and down() calls batchDelete(). The data is imported on each run

The tables in export-data-from-tables (or --export-data-from-tables) get the same code as always.

With always, each version that has data inserts its rows. A later version then inserts the rows again, over the rows of an earlier version. To prevent this, use --truncate (or truncate in the configuration) with run. Before batchInsert() imports the data of a table, it deletes all the rows of the table with DELETE FROM, in the same transaction.

Navigation

Type to search…

↑↓ navigate↵ selectEsc close