How to Create a Migration in Yii (Step-by-Step)
In this article
Migrations in Yii are a version-controlled way to manage your database schema. Instead of writing raw SQL and running it manually on each server, you define changes in PHP classes and apply them with a console command. This keeps every environment (development, staging, production) in sync and makes rollbacks possible. Before you start, you need a working Yii application (Yii 2 or Yii 1.1) and a configured database connection in your config/db.php (or protected/config/console.php for Yii 1).
What You'll Need
- A Yii project (Yii 2 or Yii 1.1) with a database connection set up.
- Command-line access to your server or local environment (terminal, SSH, or command prompt).
- Basic familiarity with PHP and your database (MySQL, PostgreSQL, etc.).
Step-by-Step
- Open your console/terminal and navigate to your Yii project's root directory. For Yii 2, the entry script is
yii(on Linux/macOS) oryii.bat(on Windows). For Yii 1.1, you useyiic(oryiic.bat). - Generate a new migration file using the built-in command. In Yii 2, run:
php yii migrate/create create_users_table
In Yii 1.1, run:php yiic migrate create create_users_table
Replacecreate_users_tablewith a descriptive name for your change. The command creates a new PHP file in theconsole/migrationsdirectory (Yii 2) orprotected/migrations(Yii 1). The filename will be prefixed with a timestamp, e.g.,m240101_123456_create_users_table.php. - Open the generated migration file in your code editor. It contains a class with two methods:
safeUp()andsafeDown(). (In Yii 1, they areup()anddown().) - Write your schema changes in
safeUp(). For example, to create auserstable with id, username, and email columns, you would write:public function safeUp() { $this->createTable('users', [ 'id' => $this->primaryKey(), 'username' => $this->string()->notNull()->unique(), 'email' => $this->string()->notNull()->unique(), ]); }In Yii 1, the syntax is slightly different, but the concept is the same. - Define the reverse operation in
safeDown(). This should undo whatsafeUp()did. For the table creation, you would drop the table:public function safeDown() { $this->dropTable('users'); }Always provide asafeDown()so you can rollback if needed. - Apply the migration by running the migrate command again. In Yii 2:
php yii migrate
In Yii 1.1:php yiic migrate
This will show a list of pending migrations. Typeyesto apply them. The migration will run and update your database schema. - Verify the change by checking your database (e.g., using phpMyAdmin or a SQL client) or by running a quick query. You should see the new table or the changes you made.
- Commit the migration file to your version control system (e.g., Git). This ensures other developers can apply the same migration to their local databases.
Common Mistakes
- Forgetting to write
safeDown()– Without it, you cannot rollback cleanly. - Using the wrong migration directory – In Yii 2, migrations live in
console/migrations; in Yii 1, they are inprotected/migrations. Placing them elsewhere will cause the command to not find them. - Not running migrations after making changes – The migration file is just a definition; you must run the command to apply it.
- Editing an already applied migration – Once a migration has been run, do not edit it. Instead, create a new migration to alter the schema further.
Tips
- Use descriptive migration names like
add_status_column_to_ordersorcreate_products_table. This makes it easier to understand the history. - Always test your migrations on a local copy of the database before deploying to production.
- If you need to add data (like default users), consider using a separate migration or a seed script, but you can also use
insert()insidesafeUp(). - In Yii 2, you can use the
--interactive=0option to apply migrations without confirmation, useful for automated deployments.
Troubleshooting
- “Migration not found” error – Make sure you are in the correct project directory and that the migration file is in the right folder. Also check that the file name matches the pattern
m<timestamp>_<name>.php. - Database connection error – Ensure your database credentials in
config/db.phpare correct and that the database server is running. Test with a simple PHP script or command-line tool. - Syntax error in migration file – Run
php -l <filename>to check for PHP syntax errors before applying. - Migration fails mid-way – Yii wraps each migration in a transaction (if your DB supports it). If a step fails, the transaction is rolled back. Fix the error and try again. If the migration was partially applied, you may need to manually revert or create a new migration to fix it.
- “Table already exists” error – This usually means you are trying to create a table that already exists. Check your database and, if needed, create a new migration to alter the existing table instead.
Frequently Asked Questions
Can I use migrations to modify existing data?
Yes, you can use the update(), insert(), and delete() methods inside safeUp() to manipulate data. However, it's often better to use a separate data migration or a seeder for large datasets.
How do I rollback a migration?
Run php yii migrate/down (Yii 2) or php yiic migrate down (Yii 1) to revert the last migration. You can specify how many steps to rollback, e.g., migrate/down 3.
Can I generate a migration from an existing database?
Yii does not have a built-in command to generate migrations from an existing schema. You would need to write the migration manually or use third-party tools.
What if I need to add a column to an existing table?
Create a new migration with a name like add_status_column_to_orders and use $this->addColumn('orders', 'status', $this->string()) in safeUp(), and $this->dropColumn('orders', 'status') in safeDown().
Do I need to run migrations on every server manually?
Yes, each environment needs the migrations applied. You can automate this in your deployment process by running the migrate command after pulling new code.
Can I use raw SQL in migrations?
Yes, you can use $this->execute('ALTER TABLE ...') for complex operations that the query builder doesn't support.