### Nullable and Length Examples Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Examples demonstrating nullable fields and specifying lengths for string columns. ```text email:string? ``` ```text email:string:unique ``` ```text email:string?[50] ``` ```text email:string:unique:EMAIL_INDEX ``` ```text email:string[120]:unique:EMAIL_INDEX ``` -------------------------------- ### Create Products Table Migration Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/installation-and-overview.md Example of a migration file that defines and creates a 'products' table with several columns. This uses the Table API to define schema changes. ```php table('products'); $table->addColumn('name', 'string', [ 'default' => null, 'limit' => 255, 'null' => false, ]); $table->addColumn('description', 'text', [ 'default' => null, 'null' => false, ]); $table->addColumn('created', 'datetime', [ 'default' => null, 'null' => false, ]); $table->addColumn('modified', 'datetime', [ 'default' => null, 'null' => false, ]); $table->create(); } } ``` -------------------------------- ### Install CakePHP Migrations Plugin Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/index.md Install the Migrations plugin using Composer. Use '@stable' for the latest stable version. ```bash php composer.phar require cakephp/migrations "@stable" # Or if composer is installed globally composer require cakephp/migrations "@stable" ``` -------------------------------- ### Modify Partitions on Existing Tables Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md Provides examples for adding and dropping partitions on an already partitioned table using `addPartitionToExisting` and `dropPartition` methods. ```php table('orders') ->addPartitionToExisting('p2025', '2026-01-01') ->update(); } public function down(): void { $this->table('orders') ->dropPartition('p2025') ->update(); } } ``` -------------------------------- ### Initialize Query Builder Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/using-the-query-builder.md Access the Query Builder by calling getQueryBuilder() with the desired statement type ('select', 'insert', 'update', 'delete'). This example demonstrates initializing a SELECT query builder. ```php getQueryBuilder('select'); $statement = $builder->select('*')->from('users')->execute(); var_dump($statement->fetchAll()); } } ``` -------------------------------- ### Install CakePHP Migrations Plugin Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/installation-and-overview.md Use Composer to install the Migrations plugin. Ensure you use the '@stable' tag for a stable release. ```bash php composer.phar require cakephp/migrations "@stable" ``` ```bash composer require cakephp/migrations "@stable" ``` -------------------------------- ### Anonymous Migration Class Example Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md An example of a migration file generated using the anonymous class style. This style avoids namespace declarations and uses a simpler file structure. ```php table('products'); $table->addColumn('name', 'string', [ 'default' => null, 'limit' => 255, 'null' => false, ]); $table->addColumn('description', 'text', [ 'default' => null, 'null' => false, ]); $table->addColumn('created', 'datetime', [ 'default' => null, 'null' => false, ]); $table->addColumn('modified', 'datetime', [ 'default' => null, 'null' => false, ]); $table->create(); } } ``` -------------------------------- ### Get All Table Columns Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/schema-introspection-and-platform-limitations.md Retrieve a list of all columns for a given table. Schema is inspected when the migration is run. ```php table('users')->getColumns(); } } ``` -------------------------------- ### View Migration Status as JSON Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Get the migration status output in JSON format for programmatic use. ```bash bin/cake migrations status --format json ``` -------------------------------- ### Generate Migration to Add a Column with a Default Value Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Use the `:default[value]` syntax to specify a default value for a new column during migration generation. This example sets the default for a boolean column to `true`. ```bash bin/cake bake migration AddActiveToUsers active:boolean:default[true] ``` -------------------------------- ### Skip Tables During Migration Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Use the 'skip' option with fnmatch() compatible patterns to exclude specific tables from drop and truncate behavior during test schema setup, such as for PostGIS tables. ```php $migrator->run(['connection' => 'test', 'skip' => ['postgis*']]); ``` -------------------------------- ### Fetch Rows from Query Results Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/executing-queries.md Utilize `fetchRow()` to retrieve a single record or `fetchAll()` to get all records from a query result. These methods accept raw SQL as their sole argument. ```php fetchRow('SELECT * FROM users'); // fetch an array of messages $rows = $this->fetchAll('SELECT * FROM messages'); } /** * Migrate Down. */ public function down(): void { } } ``` -------------------------------- ### Generate Initial Migration Snapshot Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/snapshots-and-diffs.md Use this command to create a migration file containing CREATE statements for all tables in your database. This is useful for version-controlling your initial schema. ```bash bin/cake bake migration_snapshot Initial ``` -------------------------------- ### Partitioning with Expressions Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md Shows how to partition tables using expressions, such as extracting the year from a datetime column, by utilizing the `Literal` class. ```php table('events', [ 'id' => false, 'primary_key' => ['id', 'created_at'], ]); $table->addColumn('id', 'integer', ['identity' => true]) ->addColumn('created_at', 'datetime') ->partitionBy(Partition::TYPE_RANGE, Literal::from('YEAR(created_at)')) ->addPartition('p2022', 2023) ->addPartition('p2023', 2024) ->addPartition('pmax', 'MAXVALUE') ->create(); } } ``` -------------------------------- ### Install Migrations Plugin with Composer Source: https://github.com/cakephp/migrations/blob/5.x/README.md Use Composer to add the Migrations plugin to your CakePHP application. This is the standard method for installing CakePHP plugins. ```sh composer require cakephp/migrations ``` -------------------------------- ### Create HASH Partitioned Table Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md Illustrates creating a table partitioned using HASH strategy to distribute data evenly across a specified number of partitions based on a column. ```php table('sessions'); $table->addColumn('user_id', 'integer') ->addColumn('data', 'text') ->partitionBy(Partition::TYPE_HASH, 'user_id', ['count' => 8]) ->create(); } } ``` -------------------------------- ### Preview Migrations Upgrade (Dry Run) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-to-builtin-backend.md Use this command to preview the migration upgrade process without making any actual changes to your database. ```bash bin/cake migrations upgrade --dry-run ``` -------------------------------- ### Get a Specific Table Column Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/schema-introspection-and-platform-limitations.md Retrieve a single column's definition from a table by its name. Schema is inspected when the migration is run. ```php table('users')->getColumn('email'); } } ``` -------------------------------- ### View Status for All Plugins Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Check the migration status for the application and all loaded plugins simultaneously using the --all flag. ```bash bin/cake migrations status --all ``` -------------------------------- ### Create LIST Partitioned Table (MySQL) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md Shows how to create a table partitioned by discrete values using `TYPE_LIST_COLUMNS` for string columns. This is useful for categorizing data by specific attributes like region. ```php table('customers', [ 'id' => false, 'primary_key' => ['id', 'region'], ]); $table->addColumn('id', 'integer', ['identity' => true]) ->addColumn('region', 'string', ['limit' => 20]) ->addColumn('name', 'string') ->partitionBy(Partition::TYPE_LIST_COLUMNS, 'region') ->addPartition('p_americas', ['US', 'CA', 'MX', 'BR']) ->addPartition('p_europe', ['UK', 'DE', 'FR', 'IT']) ->addPartition('p_asia', ['JP', 'CN', 'IN', 'KR']) ->create(); } } ``` -------------------------------- ### Create RANGE Partitioned Table (MySQL) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md Demonstrates creating a table partitioned by date ranges using `TYPE_RANGE_COLUMNS`. Ensure partition columns are part of the primary key for MySQL. ```php table('orders', [ 'id' => false, 'primary_key' => ['id', 'order_date'], ]); $table->addColumn('id', 'integer', ['identity' => true]) ->addColumn('order_date', 'date') ->addColumn('amount', 'decimal', ['precision' => 10, 'scale' => 2]) ->partitionBy(Partition::TYPE_RANGE_COLUMNS, 'order_date') ->addPartition('p2022', '2023-01-01') ->addPartition('p2023', '2024-01-01') ->addPartition('p2024', '2025-01-01') ->addPartition('pmax', 'MAXVALUE') ->create(); } } ``` -------------------------------- ### Create KEY Partitioned Table (MySQL only) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md Demonstrates KEY partitioning, which is similar to HASH but uses MySQL's internal hashing function. This is specific to MySQL. ```php table('cache', [ 'id' => false, 'primary_key' => ['cache_key'], ]); $table->addColumn('cache_key', 'string', ['limit' => 255]) ->addColumn('value', 'binary') ->partitionBy(Partition::TYPE_KEY, 'cache_key', ['count' => 16]) ->create(); } } ``` -------------------------------- ### Run Migrations Upgrade Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-to-builtin-backend.md Execute the command to perform the actual migration from Phinx log tables to the unified `cake_migrations` table. ```bash bin/cake migrations upgrade ``` -------------------------------- ### Scope Migrations to a Plugin Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Use the --plugin or -p option to run migration commands for a specific plugin. ```bash bin/cake migrations status -p PluginName bin/cake migrations migrate -p PluginName ``` -------------------------------- ### Run Basic Migrations Commands Programmatically Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Instantiate the Migrations class to run common migration commands like status, migrate, rollback, markMigrated, and seed from a non-shell environment. ```php use Migrations\Migrations; $migrations = new Migrations(); $status = $migrations->status(); $migrate = $migrations->migrate(); $rollback = $migrations->rollback(); $markMigrated = $migrations->markMigrated(20150804222900); $seeded = $migrations->seed(); ``` -------------------------------- ### Initialize Migrations with Default Parameters Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Pass an array of default parameters to the Migrations constructor to apply them to all subsequent method calls. ```php use Migrations\Migrations; $migrations = new Migrations([ 'connection' => 'custom', 'source' => 'MyMigrationsFolder', ]); $status = $migrations->status(); $migrate = $migrations->migrate(); ``` -------------------------------- ### Column Definition Pattern Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Understand the pattern for defining columns on the command line. ```text fieldName:fieldType?[length]:default[value]:indexType:indexName ``` -------------------------------- ### Generate Migration to Create a Table Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Use the `bin/cake bake migration` command with column definitions to generate a migration file for creating a new table. This command automatically includes column definitions for specified fields. ```bash bin/cake bake migration CreateProducts name:string description:text created modified ``` -------------------------------- ### Create a New Table with Columns and Indexes Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md Defines a new 'users' table with multiple string columns, datetime columns, and a unique index on username and email. Automatically includes an 'id' primary key. ```php table('users'); $users->addColumn('username', 'string', ['limit' => 20]) ->addColumn('password', 'string', ['limit' => 40]) ->addColumn('email', 'string', ['limit' => 100]) ->addColumn('created', 'datetime') ->addColumn('updated', 'datetime', ['null' => true]) ->addIndex(['username', 'email'], ['unique' => true]) ->create(); } } ``` -------------------------------- ### Apply All Migrations Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Use this command to apply all pending database migrations. ```bash bin/cake migrations migrate ``` -------------------------------- ### Run Migrations Upgrade and Drop Tables Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-to-builtin-backend.md This command upgrades the migrations and then drops the old `phinxlog` tables. Use with caution after verifying migrations. ```bash bin/cake migrations upgrade --drop-tables ``` -------------------------------- ### Generate Snapshot for a Plugin Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/snapshots-and-diffs.md Use the --plugin option to generate a migration snapshot for a specific plugin. Only tables with defined Table object model classes will be included. ```bash bin/cake bake migration_snapshot Initial --plugin MyPlugin ``` -------------------------------- ### Create a New Migration File Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Use the `bin/cake bake migration` command to generate a new, empty migration file. You can then edit this file to define your schema changes. ```bash bin/cake bake migration CreateProducts ``` -------------------------------- ### Run Migrations from a Custom Source Directory Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Execute migrations located in a directory other than the default using the --source option. ```bash bin/cake migrations migrate -s Alternate ``` -------------------------------- ### Generate Snapshot from Specific Connection Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/snapshots-and-diffs.md Specify a different database connection to use when generating the migration snapshot using the --connection option. ```bash bin/cake bake migration_snapshot Initial --connection my_other_connection ``` -------------------------------- ### Iterating and Fetching Query Results Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/using-the-query-builder.md Shows how to iterate over query results directly or fetch all results into an associative array. ```php execute()->fetchAll('assoc'); ``` -------------------------------- ### Run Migrations with Custom Options Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Pass an array of parameters to migration methods to customize their execution, such as specifying a connection or migration source. ```php use Migrations\Migrations; $migrations = new Migrations(); $status = $migrations->status([ 'connection' => 'custom', 'source' => 'MyMigrationsFolder', ]); ``` -------------------------------- ### Use Fluent Index Builder Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Leverage the fluent `BaseMigration::index()` builder for a more readable and chainable way to define complex index properties like type, name, and order. ```php $this->table('users') ->addIndex( $this->index(['email', 'username']) ->setType('unique') ->setName('idx_users_email') ->setOrder(['email' => 'DESC', 'username' => 'ASC']) ) ->save(); ``` -------------------------------- ### Apply Migrations to a Specific Version Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Migrate your database to a specific version using the --target option. ```bash bin/cake migrations migrate -t 20150103081132 ``` -------------------------------- ### Run Migrations for a Specific Plugin Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Apply migrations for a particular plugin using the --plugin option. ```bash bin/cake migrations migrate -p MyAwesomePlugin ``` -------------------------------- ### Specify Connection for Seed Generation Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Use the --connection option to specify an alternative database connection for generating the seed. ```bash bin/cake bake seed Articles --connection connection ``` -------------------------------- ### Apply Migrations using CLI Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/installation-and-overview.md Execute migrations to apply the defined database schema changes to your database. This command should be run from your application's root directory. ```bash bin/cake migrations migrate ``` -------------------------------- ### Generate Migration Diff Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/snapshots-and-diffs.md Create a migration file that captures the differences between the current database schema and a schema dump file. This is useful for synchronizing manual schema changes. ```bash bin/cake bake migration_diff NameOfTheMigrations ``` -------------------------------- ### Using CONCAT SQL Function Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/using-the-query-builder.md Demonstrates using the CONCAT SQL function with a mix of literal and bound parameters. Arguments are treated as bound parameters unless marked as literal. ```php func()->concat([ 'title' => 'literal', ' NEW' ]); $query->select(['title' => $concat]); ``` -------------------------------- ### Run Migrations Against a Different Database Connection Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Apply migrations using a specific database connection defined in your configuration with the --connection option. ```bash bin/cake migrations migrate -c my_custom_connection ``` -------------------------------- ### Generate Migration with Default, Nullable, and Unique Constraints Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md This command demonstrates combining multiple column constraints in a single migration generation command. It adds a 'status' column with a default value, marked as unique. ```bash bin/cake bake migration AddStatusToOrders status:string:default['pending']:unique ``` -------------------------------- ### Configure for Rollback to Phinx Tables Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-to-builtin-backend.md To revert to using Phinx tables after upgrading, set `'legacyTables' => true` in your `config/app.php`. ```php // config/app.php 'Migrations' => [ 'legacyTables' => true, ] ``` -------------------------------- ### Manually Create Schema Dump File Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/snapshots-and-diffs.md Before generating a diff on an application with an existing migration history, manually create a schema dump file using this command. This file serves as the baseline for comparison. ```bash bin/cake migrations dump ``` -------------------------------- ### Running Multiple Seed Classes Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Execute multiple seed classes by listing their names, separated by commas, as arguments to the `seeds run` command. ```bash bin/cake seeds run User,Permission,Log ``` ```bash bin/cake seeds run UserSeed,PermissionSeed,LogSeed ``` -------------------------------- ### Create Empty Migration Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Generate an empty migration file for full manual control over schema changes. ```bash bin/cake migrations create MyCustomMigration ``` -------------------------------- ### Specify Plugin for Seed Generation Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Use the --plugin option to specify the plugin into which the seed file should be baked. ```bash bin/cake bake seed Articles --plugin PluginName ``` -------------------------------- ### Add Integer Columns with Specific Limits (MySQL) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md Demonstrates adding integer columns with specific size limits using MySQL adapter constants. This is useful for optimizing storage or adhering to specific database constraints. ```php table('cart_items'); $table->addColumn('user_id', 'integer') ->addColumn('product_id', 'integer', ['limit' => MysqlAdapter::INT_BIG]) ->addColumn('subtype_id', 'integer', ['limit' => MysqlAdapter::INT_SMALL]) ->addColumn('quantity', 'integer', ['limit' => MysqlAdapter::INT_TINY]) ->create(); ``` -------------------------------- ### Load Migrations Plugin for CLI Source: https://github.com/cakephp/migrations/blob/5.x/README.md Load the Migrations plugin for command-line interface (CLI) usage. This ensures the plugin's shells are available. ```sh bin/cake plugin load Migrations --only-cli ``` -------------------------------- ### Adding Backward Compatibility Aliases Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-to-builtin-backend.md Add command aliases in `src/Application.php` to maintain compatibility with old migration commands for existing scripts or CI/CD pipelines. ```php public function console(CommandCollection $commands): CommandCollection { // Add your application's commands $commands = $this->addConsoleCommands($commands); // Add backward compatibility aliases for migrations 4.x commands $commands->add('migrations seed', \Migrations\Command\SeedCommand::class); return $commands; } ``` ```php // Add multiple backward compatibility aliases $commands->add('migrations seed', \Migrations\Command\SeedCommand::class); $commands->add('migrations seed:run', \Migrations\Command\SeedCommand::class); $commands->add('migrations seed:status', \Migrations\Command\SeedStatusCommand::class); ``` -------------------------------- ### Add a Simple Index to a Table Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Use `addIndex()` to create a basic index on a specified column. This is the most straightforward way to add an index. ```php table('users') ->addColumn('city', 'string') ->addIndex(['city']) ->save(); } } ``` -------------------------------- ### Generate Migration to Add a Column Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Use this command to generate a migration file for adding a new column to an existing table. Specify the table name, column name, and its type. ```bash bin/cake bake migration AddPriceToProducts price:decimal[5,2] ``` -------------------------------- ### Run Migrations for Tests Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Use the Migrator class in tests/bootstrap.php to build schema for your tests. It can run migrations for the main application, specific plugins, or different database connections. ```php // in tests/bootstrap.php use Migrations\TestSuite\Migrator; $migrator = new Migrator(); // Simple setup with no plugins $migrator->run(); // Run a non-test database $migrator->run(['connection' => 'test_other']); // Run migrations for plugins $migrator->run(['plugin' => 'Contacts']); // Run the Documents migrations on the test_docs connection $migrator->run(['plugin' => 'Documents', 'connection' => 'test_docs']); ``` -------------------------------- ### Adapter Query Result Changes (4.x vs 5.x) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-from-4-x.md Illustrates the difference in fetching query results using `AdapterInterface::query()` between Migrations 4.x (using phinx results) and 5.x (using `Cake\Database\StatementInterface`). Note the change in fetching methods. ```php // 4.x (phinx) $stmt = $this->getAdapter()->query('SELECT * FROM articles'); $rows = $stmt->fetchAll(); $row = $stmt->fetch(); ``` ```php // 5.x (builtin) $stmt = $this->getAdapter()->query('SELECT * FROM articles'); $rows = $stmt->fetchAll('assoc'); $row = $stmt->fetch('assoc'); ``` -------------------------------- ### Add Backward Compatibility Alias for 'migrations seed' Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-from-4-x.md Shows how to add a command alias in `src/Application.php` to maintain the old `migrations seed` command for backward compatibility with existing scripts or CI/CD pipelines. ```php public function console(CommandCollection $commands): CommandCollection { $commands = $this->addConsoleCommands($commands); // Add backward compatibility alias $commands->add('migrations seed', \Migrations\Command\SeedCommand::class); return $commands; } ``` -------------------------------- ### Run Multiple Migration Sets Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Utilize the runMany() method to execute multiple sets of migrations, useful when dealing with various plugins or database configurations. ```php $migrator->runMany([ ['plugin' => 'Contacts'], ['plugin' => 'Documents', 'connection' => 'test_docs'], ]); ``` -------------------------------- ### Load Migrations Plugin in Application.php Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/installation-and-overview.md Alternatively, load the Migrations plugin directly within your application's main configuration file. ```php $this->addPlugin('Migrations'); ``` -------------------------------- ### Configuring Legacy Migrations Tables Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-to-builtin-backend.md Configure the `Migrations.legacyTables` option in `config/app.php` or `config/app_local.php` to control the use of new `cake_migrations` or legacy `phinxlog` tables. ```php // config/app.php or config/app_local.php 'Migrations' => [ // null (default): Autodetect - use legacy if phinxlog tables exist // false: Force use of new cake_migrations table // true: Force use of legacy phinxlog tables 'legacyTables' => null, ], ``` -------------------------------- ### View Migration Status Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Check the current status of all database migrations. ```bash bin/cake migrations status ``` -------------------------------- ### Mark All Migrations Using Special Value Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Use the special value 'all' to mark every migration as migrated. ```bash bin/cake migrations mark_migrated all ``` -------------------------------- ### Generate Seed with Data from Table Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Use the --data option to include data from the specified table directly into the generated seed file. ```bash bin/cake bake seed --data Articles ``` -------------------------------- ### PHP Code for Adding Columns with Indexes Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md This migration code adds multiple columns and includes both a simple index and a unique index on specified columns. It demonstrates chaining `addColumn` and `addIndex` methods. ```php table('products'); $table->addColumn('name', 'string') ->addColumn('email', 'string') ->addIndex(['name']) // add a unique index: ->addIndex('email', ['unique' => true]) ->update(); } } ``` -------------------------------- ### Check and Drop Check Constraints Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Shows how to verify the existence of a check constraint using `hasCheckConstraint()` and remove it with `dropCheckConstraint()`. ```php $table = $this->table('products'); if ($table->hasCheckConstraint('price_positive')) { $table->dropCheckConstraint('price_positive') ->save(); } ``` -------------------------------- ### Migrating Seed Commands Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-to-builtin-backend.md Compares old and new command structures for running seed classes. Use the new commands for CakePHP migrations 5.x and later. ```bash # Old (4.x and earlier) bin/cake migrations seed bin/cake migrations seed --seed Articles # New (5.x and later) bin/cake seeds run bin/cake seeds run Articles ``` -------------------------------- ### Generate Migration to Add a Column with an Index Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md This command generates a migration that adds a column and an index to it. The `:index` suffix indicates that an index should be created for the specified column. ```bash bin/cake bake migration AddNameIndexToProducts name:string:index ``` -------------------------------- ### Create a Foreign Key using Fluent Builder Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Utilizes a fluent builder for defining foreign keys, offering a more readable syntax for complex configurations. Requires importing ForeignKey class. ```php table('articles') ->addForeignKey( $this->foreignKey() ->setColumns('user_id') ->setReferencedTable('users') ->setReferencedColumns('user_id') ->setDelete(ForeignKey::CASCADE) ->setName('article_user_fk') ) ->save(); } } ``` -------------------------------- ### Configure Legacy Tables Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-to-builtin-backend.md Update your `config/app.php` to disable the use of legacy Phinx tables after a successful upgrade. ```php // config/app.php 'Migrations' => [ 'legacyTables' => false, ], ``` -------------------------------- ### Mark All Migrations as Migrated Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Mark all existing migrations as applied without actually running them. ```bash bin/cake migrations mark_migrated ``` -------------------------------- ### Running Seed Classes with Verbose Output Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Use the `-v` parameter with the `seeds run` command to increase the output verbosity, providing more details during the seeding process. ```bash bin/cake seeds run -v ``` -------------------------------- ### Add a Unique, Named, and Ordered Index Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Configure indexes with `unique` constraints, custom `name`, and specific `order` for multi-column indexes. This provides more control over index behavior and identification. ```php $this->table('users') ->addColumn('email', 'string') ->addColumn('username', 'string') ->addIndex(['email', 'username'], [ 'unique' => true, 'name' => 'idx_users_email', 'order' => ['email' => 'DESC', 'username' => 'ASC'], ]) ->save(); ``` -------------------------------- ### Mark Migrations Up to a Specific Version Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Mark all migrations up to a specified version as migrated using the --target option. ```bash bin/cake migrations mark_migrated --target=20151016204000 ``` -------------------------------- ### Running a Specific Seed Class Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md To run a single seed class, provide its name as an argument to the `seeds run` command. You can use either the short name (without the 'Seed' suffix) or the full class name. ```bash bin/cake seeds run User ``` ```bash bin/cake seeds run UserSeed ``` -------------------------------- ### CakePHP Migrations Commands (5.x) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/upgrades/upgrading-from-4-x.md Lists the available commands for managing migrations and seeds in CakePHP 5.x. These commands are used for applying, rolling back, and checking the status of database migrations and seeds. ```bash bin/cake migrations migrate bin/cake migrations rollback bin/cake migrations status bin/cake migrations mark_migrated bin/cake migrations dump ``` ```bash bin/cake seeds run bin/cake seeds run SeedName bin/cake seeds status bin/cake seeds reset ``` -------------------------------- ### Generate Diff from Specific Connection Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/snapshots-and-diffs.md Specify a different database connection to use when generating the migration diff using the --connection option. ```bash bin/cake bake migration_diff NameOfTheMigrations --connection my_other_connection ``` -------------------------------- ### Using COUNT Aggregate Function Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/using-the-query-builder.md Use the func() method to create aggregate functions like COUNT. The arguments are treated as literal values. ```php select(['count' => $builder->func()->count('*')]); ``` -------------------------------- ### Create MySQL Fulltext Index Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Implement `fulltext` indexes for efficient text searching in MySQL. Ensure the table uses the `MyISAM` engine for versions before 5.6. ```php $table = $this->table('users', ['engine' => 'MyISAM']); $table->addColumn('email', 'string') ->addIndex('email', ['type' => 'fulltext']) ->create(); ``` -------------------------------- ### Running All Seed Classes Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Execute all available seed classes in your project using the `seeds run` command in the CakePHP console. ```bash bin/cake seeds run ``` -------------------------------- ### Run Migrations and Clear Schema Cache Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Execute pending database migrations and clear the ORM schema cache. This should be part of your deployment script. ```bash bin/cake migrations migrate bin/cake schema_cache clear ``` -------------------------------- ### Implement Idempotent Seed Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Override the `isIdempotent()` method to return `true` for seeds that can be run multiple times safely. The `run()` method should handle potential duplicate executions. ```php execute(" INSERT INTO settings (setting_key, setting_value) VALUES ('app_version', '2.0.0') ON DUPLICATE KEY UPDATE setting_value = '2.0.0' "); // Or check before inserting $exists = $this->fetchRow( "SELECT COUNT(*) as count FROM settings WHERE setting_key = 'maintenance_mode'" ); if ($exists['count'] === 0) { $this->table('settings')->insert([ 'setting_key' => 'maintenance_mode', 'setting_value' => 'false', ])->save(); } } } ``` -------------------------------- ### Mark Migrations Using Positional Argument Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Mark migrations as migrated by providing the version number as a positional argument. ```bash bin/cake migrations mark_migrated 20150420082532 ``` -------------------------------- ### Traditional Seed Class Structure Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md A standard seed class extends Migrations\BaseSeed and implements the run() method for database seeding. ```php where(['id >' => 1])->andWhere(['title' => 'My Title']); // Equivalent to $builder->where(['id >' => 1, 'title' => 'My title']); // WHERE id > 1 OR title = 'My title' $builder->where(['OR' => ['id >' => 1, 'title' => 'My title']]); ``` -------------------------------- ### Define Upward Migration Logic Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/migration-methods.md The `up()` method contains the logic to transform the database when migrating upwards. It is executed if the migration has not been run before. ```php table('tableName'); } public function down() { } } ``` -------------------------------- ### Define Reversible Migrations with change() Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/migration-methods.md Use the `change()` method for reversible migrations. Migrations automatically generates rollback operations for supported actions like creating, renaming, adding columns, indexes, and foreign keys. When `change()` is present, `up()` and `down()` are ignored. ```php table('user_logins'); $table->addColumn('user_id', 'integer') ->addColumn('created', 'datetime') ->create(); } } ``` -------------------------------- ### Specify Fields for Seed Generation Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Use the --fields option with --data to specify a comma-separated list of fields to include from the table in the seed file. ```bash # Will only export the fields `id`, `title` and `excerpt` bin/cake bake seed --data --fields id,title,excerpt Articles ``` -------------------------------- ### Define Seed Dependencies Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Implement the `getDependencies()` method to specify an ordered list of seeds that must run before the current seed. This is crucial for maintaining data integrity and avoiding foreign key constraint violations. ```php 'USD', 'name' => 'US Dollar'], ['code' => 'EUR', 'name' => 'Euro'], ]; $this->table('currencies') ->insertOrSkip($data) ->saveData(); } } ``` -------------------------------- ### Create Index Concurrently (PostgreSQL) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Add indexes concurrently in PostgreSQL to avoid locking the table during creation. This is crucial for maintaining application availability during schema changes. ```php $this->table('users') ->addColumn('email', 'string') ->addIndex( $this->index('email') ->setName('user_email_unique_idx') ->setType('unique') ->setConcurrently(true) ) ->create(); ``` -------------------------------- ### Add Include Columns to Index (SQL Server/PostgreSQL) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Utilize the `include` option for non-key columns in indexes on SQL Server and PostgreSQL. This can improve query performance by allowing index-only scans. ```php $this->table('users') ->addColumn('email', 'string') ->addColumn('firstname', 'string') ->addColumn('lastname', 'string') ->addIndex(['email'], ['include' => ['firstname', 'lastname']]) ->create(); ``` -------------------------------- ### Add Hash Index for Equality Comparisons Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/indexes-and-constraints.md Use the 'hash' type for simple equality comparisons. B-tree indexes also handle equality efficiently. ```php $this->table('sessions') ->addColumn('session_id', 'string', ['limit' => 64]) ->addIndex('session_id', ['type' => 'hash']) ->create(); ``` -------------------------------- ### Basic WHERE Conditions Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/using-the-query-builder.md Add simple equality or inequality conditions to the WHERE clause. Operators can be appended to the field name with a space. ```php // WHERE id = 1 $builder->where(['id' => 1]); // WHERE id > 1 $builder->where(['id >' => 1]); ``` -------------------------------- ### Execute and Query SQL Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/executing-queries.md Use `execute()` for statements that modify data and return affected row counts, and `query()` for SELECT statements returning results. Both support prepared statements with a parameter array. ```php execute('DELETE FROM users'); // returns the number of affected rows // query() $stmt = $this->query('SELECT * FROM users'); // returns PDOStatement $rows = $stmt->fetchAll(); // returns the result as an array // using prepared queries $count = $this->execute('DELETE FROM users WHERE id = ?', [5]); $stmt = $this->query('SELECT * FROM users WHERE id > ?', [5]); // returns PDOStatement $rows = $stmt->fetchAll(); } /** * Migrate Down. */ public function down(): void { } } ``` -------------------------------- ### Add a Column First in CakePHP Migrations (MySQL) Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/writing-migrations/columns-and-table-operations.md To place a new column at the beginning of a table with the MySQL adapter, use the ` Migrations\Db\Adapter\MysqlAdapter::FIRST` constant. ```php $this->table('users') ->addColumn('city', 'string', ['after' => Migrations Db Adapter MysqlAdapter::FIRST]) ->update(); ``` -------------------------------- ### Generate Migration to Remove a Column Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Use this command to generate a migration for removing a column. The migration name must follow the pattern `RemoveXXXFromYYY`. ```bash bin/cake bake migration RemovePriceFromProducts price ``` -------------------------------- ### Load Migrations Plugin with PendingMigrations Middleware Source: https://github.com/cakephp/migrations/blob/5.x/README.md Load the Migrations plugin when using the PendingMigrations middleware. This integrates the plugin's functionality with your application's request lifecycle. ```sh bin/cake plugin load Migrations ``` -------------------------------- ### Generate an Anonymous Seed Class Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Use the --style anonymous option with the bake command to generate an anonymous seed class. ```bash bin/cake bake seed MyNewSeed --style anonymous ``` -------------------------------- ### Mark Migrations Excluding a Target Version Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/running-and-managing-migrations.md Mark migrations up to a target version, but exclude the target version itself from being marked, using the --exclude flag. ```bash bin/cake migrations mark_migrated --target=20151016204000 --exclude ``` -------------------------------- ### Skip Schema Lock File Generation Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/advanced/integration-and-deployment.md Use the --no-lock option with migration commands to prevent the generation of the schema.lock file. This is useful for deployment scenarios where tracking schema state via this file is not desired. ```bash bin/cake migrations migrate --no-lock ``` ```bash bin/cake migrations rollback --no-lock ``` ```bash bin/cake bake migration_snapshot MyMigration --no-lock ``` -------------------------------- ### Creating a Delete Query Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/using-the-query-builder.md Constructs a DELETE query to remove records from a table. Specify the table and the conditions for deletion. ```php getQueryBuilder('delete'); $builder ->delete('users') ->where(['accepted_gdpr' => false]) ->execute(); ``` -------------------------------- ### Generate Anonymous Migration Class Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/getting-started/creating-migrations.md Use the `--style anonymous` option with `bin/cake bake migration` to generate a migration file using PHP's anonymous class feature. This is useful for avoiding namespace declarations and simplifying file structure. ```bash bin/cake bake migration CreateProducts --style anonymous ``` -------------------------------- ### Specify Table for Seed Generation Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Use the --table option to specify the exact table name that the generated seed file will alter. ```bash bin/cake bake seed articles --table my_articles_table ``` -------------------------------- ### SQL Equivalent of Combined Expressions Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/using-the-query-builder.md This SQL shows the output of combining expressions with OR and NOT logic. ```sql SELECT * FROM articles WHERE NOT (author_id = 2 OR author_id = 5) AND view_count <= 10 ``` -------------------------------- ### Customize Seed Tracking Table Name Source: https://github.com/cakephp/migrations/blob/5.x/docs/en/guides/seeding.md Configure a custom table name for tracking seed execution in your `config/app.php` or `config/app_local.php` file. ```php 'Migrations' => [ 'seed_table' => 'my-custom-seeds-table', ] ```