yii2 migration add column
To add a column using Yii2 migration, you can follow these steps:
Open the migration file for the table you want to modify. Migration files are typically located in the
migrations
directory of your Yii2 application.Inside the
up()
method of the migration file, use theaddColumn()
method to add a new column. TheaddColumn()
method takes three parameters: the table name, the column name, and the column definition.
public function up()
{
$this->addColumn('{{%table_name}}', 'column_name', $this->columnDefinition);
}
Replace {{%table_name}}
with the actual name of the table where you want to add the column. Replace 'column_name'
with the name of the new column you want to add. And replace $this->columnDefinition
with the definition of the column, such as its data type, length, default value, etc.
For example, to add a column named email
of type string
with a maximum length of 255 characters and a default value of NULL
, you can use the following code:
public function up()
{
$this->addColumn('{{%users}}', 'email', $this->string(255)->defaultValue(null));
}
- Save the migration file and run the migration command to apply the changes to the database. You can use the following command in the terminal:
php yii migrate
This will run all pending migrations and apply the changes to the database.
That's it! The new column should now be added to the specified table in your Yii2 application.