How to create migrations in yii 2 framework

How to create migrations in yii 2 framework
Reading Time: 2 minutes

Most of our web application are database driven. In Yii 2, there is a feature which helps to deal with database structure at the code level. It keeps track of everything and changes the whole application. Migrations help a lot while working with the team.

Steps to create migrations in yii 2

Migrations are useful in creating the table in Yii 2. Type yii help migrate command in cmd to get usage of each migrate command. Let’s start creating migration now.

  1. To create new migration, open cmd and move to your app path. for eg: cd c:/xampp/htdocs/test_yii. after this type yii migrate/create create_student_table in cmd. In this create_student_table is the name of migration. It can be anything you wish to write. after running this command, One file will be generated in your migrations folder. You have to open that file code. The code will look somewhat like below code. The migration class name is automatically generated in the format of m<YYMMDD_HHMMSS>_<Name>.

     
  2. In the above there are two function, up function will call when you will upgrade your database by typing this command yii migrate/up and down function will call when you will downgrade your database by typing this command yii migrate/down. Now we will write the fields name of student table in up() which we want to create. See the below code.

    In the above code, I have used newly introduced schema builder in yii 2. It is a convenient way to define column schema. Read more about this here. Or we can use another schema which is used earlier. You can read more about that here. See the sample code below
  3. Now to create tables in database, you have to run yii migrate/up and it will create new table student in database. To drop the table, we can run the down() function as we have defined the drop command in down(). To run the down() function, we have to write yii migrate/down. It will drop the above created table.
  4. Now if you want to change any schema of any database field then just change in code and run the yii migrate/up code and your field in database will changed. You can read full documention at yii 2 official website. If you face any problem then ask your problem in comments.

One Comment on “How to create migrations in yii 2 framework”

Leave a Reply

Your email address will not be published. Required fields are marked *