How to Create And Apply Yii 2 Migrations?

10 minutes read

Yii 2 is a PHP framework that provides a powerful tool called migrations for managing database-related changes. Migrations allow you to create and apply changes to your database schema in a version-controlled manner. Here's a brief explanation on how to create and apply Yii 2 migrations without using list items:

  1. Create a new migration: To create a new migration, you need to run the yii migrate/create command in your terminal or command prompt followed by the name of the migration. For example, yii migrate/create create_users_table.
  2. Edit the migration file: Yii 2 will create a new migration file under the migrations directory. Open the generated migration file and locate the up() method. Inside this method, you can write the necessary code to create or modify database tables, columns, indexes, etc. Use Yii's database schema builder or execute raw SQL statements to define your changes.
  3. Applying the migration: You can apply the migration by running the yii migrate command in your terminal or command prompt. This command will execute all the available migrations that have not been applied yet. Yii will keep track of the applied migrations in your database and only execute the pending ones.
  4. Rollback the migration: In case you need to revert a migration, Yii provides an easy way to rollback the changes. Use the yii migrate/down command followed by the number of migrations you want to rollback. For example, yii migrate/down 1 will revert the last applied migration.
  5. Additional migration commands: Yii provides other commands to control migrations, such as yii migrate/history to show the migration history, yii migrate/new to show the new migrations that haven't been applied yet, and yii migrate/to to apply or rollback migrations up to a specific version.


Remember to always review and test your migrations properly before applying them to production environments. Migrations are vital for maintaining a consistent database schema as your application evolves.

Best Yii 2 Frameworks Books to Read in 2024

1
Yii 2 Development: Bring A Map Through The Halls Of Yii 2 Development

Rating is 5 out of 5

Yii 2 Development: Bring A Map Through The Halls Of Yii 2 Development

2
Yii2 Quick Start Guide - Mastering Yii 2

Rating is 4.9 out of 5

Yii2 Quick Start Guide - Mastering Yii 2

3
Yii 2 Speed: Getting Up To Speed With Yii 2

Rating is 4.8 out of 5

Yii 2 Speed: Getting Up To Speed With Yii 2


How to insert data into a table using a migration in Yii 2?

To insert data into a table using a migration in Yii 2, you can use the insert() method of the yii\db\Migration class. Here's how you can do it:

  1. Create a new migration file using the yii migrate/create command. For example:
1
yii migrate/create insert_data_into_table


  1. Open the newly created migration file located in the migrations directory. It will have a name like mYYMMDD_HHmmss_insert_data_into_table.php.
  2. Inside the up() method, use the insert() method to insert data into the desired table. For example:
1
2
3
4
5
6
7
public function up()
{
    $this->insert('table_name', [
        'column1' => 'value1',
        'column2' => 'value2',
    ]);
}


Replace table_name with the actual name of the table, and provide the appropriate column names and values for the row you want to insert.

  1. Save the migration file.
  2. Run the migration using the yii migrate command:
1
yii migrate


This will execute the migration and insert the specified data into the table.


How to create a new migration in Yii 2?

To create a new migration in Yii 2, you can follow these steps:

  1. Open your command-line interface and navigate to the root directory of your Yii 2 application.
  2. Run the following command to create a new migration file: ./yii migrate/create migration_name Replace "migration_name" with a descriptive name for your migration.
  3. A new migration file will be created in the "migrations" folder of your application. The file will be named with a timestamp and the migration name you provided.
  4. Open the newly created migration file using a text editor. The migration file will contain an empty "up()" method and a "down()" method. The "up()" method is used to apply the changes to your database schema, while the "down()" method is used to rollback the changes.
  5. Inside the "up()" method, you can write the code to create or modify database tables, columns, indexes, etc. You can use Yii 2's query builder or raw SQL queries to perform the necessary changes.
  6. Inside the "down()" method, you should write code to revert the changes made in the "up()" method. For example, if you added a new table, you should drop that table in the "down()" method.
  7. Save the migration file.
  8. To apply the changes to your database, run the following command in your command-line interface: ./yii migrate This will execute all the pending migrations and update your database schema.


Note: Make sure your database connection configuration is properly set in Yii 2's config/db.php file, as the migration commands use this configuration to connect to the database.


How to rollback a migration in Yii 2?

To rollback a migration in Yii 2, you can use the following steps:

  1. Open your command line interface (e.g., Terminal or Command Prompt) and navigate to the root folder of your Yii 2 application.
  2. Run the following command to rollback the most recent migration:
1
php yii migrate/down


This command will revert the changes made by the most recent migration file.

  1. Alternatively, if you want to rollback multiple migrations, you can specify the number of migrations to rollback. For example, to rollback the last 3 migrations, run the following command:
1
php yii migrate/down 3


  1. Yii 2 will prompt you to confirm the rollback. Type "yes" and press Enter to proceed with the rollback.


Note that the rollback operation only works if the rollback functionality is properly implemented in the migration files. If the migration files do not support rollback, the above steps might not work as expected.

Best Yii 2 Cloud Hosting Providers in 2024

1
DigitalOcean

Rating is 5 out of 5

DigitalOcean

2
AWS

Rating is 4.9 out of 5

AWS

3
Vultr

Rating is 4.8 out of 5

Vultr

4
Cloudways

Rating is 4.7 out of 5

Cloudways


How to rename a column in Yii 2 migration?

To rename a column in Yii 2 migration, you can use the renameColumn method of the yii\db\Migration class.


Here's an example of how to rename a column in a migration:

  1. Create a new migration file using the yii migrate/create command in your project's console:
1
yii migrate/create rename_column_in_table_name


  1. Open the newly created migration file and add the following code to the up method:
1
2
3
4
5
6
7
8
public function up()
{
    $table = 'table_name';
    $oldColumnName = 'old_column_name';
    $newColumnName = 'new_column_name';
    
    $this->renameColumn($table, $oldColumnName, $newColumnName);
}


Replace table_name, old_column_name, and new_column_name with the actual table name, old column name, and new column name respectively.

  1. Add the following code to the down method to revert the column rename operation:
1
2
3
4
5
6
7
8
public function down()
{
    $table = 'table_name';
    $newColumnName = 'new_column_name';
    $oldColumnName = 'old_column_name';

    $this->renameColumn($table, $newColumnName, $oldColumnName);
}


  1. Run the migration using the yii migrate command in your project's console:
1
yii migrate


After running the migration, the specified column will be renamed accordingly.


What is the naming convention for migration files in Yii 2?

In Yii 2, the naming convention for migration files is as follows:

  1. For creating a new migration: The file name should start with "m" followed by a timestamp in the format "YmdHis" (YearMonthDayHourMinuteSecond). For example, "m210630_120000_create_table.php".
  2. For modifying an existing migration: The file name should start with "m" followed by the timestamp of the original migration, followed by an underscore, and a short description of the modification. For example, "m210630_120000_modify_table.php".


By following this naming convention, Yii 2 can easily identify and execute the migrations in the correct order based on the timestamps.

Facebook Twitter LinkedIn Telegram

Related Posts:

In Yii 2, migrations are used to manage the database schema in an organized and version-controlled manner. Migrations allow you to create, modify, and delete database tables, columns, indexes, and foreign keys using PHP code.To create a new migration, you need...
Yii 2 is a powerful PHP framework that allows developers to easily create web applications. One of the key features of Yii 2 is the ability to create and apply console commands. Console commands are scripts that can be executed via the command line, allowing d...
To install Yii 2 framework, follow these steps:Ensure that your system meets the minimum requirements for Yii 2. These include PHP 5.4 or later and various PHP extensions such as PDO, OpenSSL, and Mbstring. Download the latest version of Yii 2 from the officia...