Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new column with Yii 2 migrations on a specific position in a table?

Let's say I have this table structure:

+----+------------+-----------+---------+------+---------+---------+---------------------+---------------------+
| id | first_name | last_name | country | city | address | zipcode | created             | updated             |
+----+------------+-----------+---------+------+---------+---------+---------------------+---------------------+
|  1 | Duvdevan   | Duvdevani | NULL    | NULL | NULL    | NULL    | 2016-02-12 15:37:19 | 2016-02-12 16:35:57 |
+----+------------+-----------+---------+------+---------+---------+---------------------+---------------------+

And I want to add a new column called email, just after id and before first_name, using the addColumn method of the Migration class.

Only thing I can do in my new migration is:

public function up()
{
    $this->addColumn('contacts', 'email', $this->string(64));
}

And it will put it at the end of the table, after updated field.

How can I add a column at a specific position within my table, so this SQL query could be respected:

ALTER TABLE contacts ADD email VARCHAR(64) AFTER id
like image 219
Zlatan Omerović Avatar asked Feb 13 '16 12:02

Zlatan Omerović


People also ask

How do I run a specific migration in yii2?

To run specific migration, you can mark(skip) migrations upto just before one you want run. You can mark migration by using one of following command: Using timestamp to specify the migration yii migrate/mark 150101_185401. Using a string that can be parsed by strtotime() yii migrate/mark "2015-01-01 18:54:01"


1 Answers

Solved it. If anyone faces the same issue, this is the solution I used:

public function up()
{
    $this->addColumn('contacts', 'email', 'VARCHAR(64) AFTER id');
}

EDIT: From version Yii 2.0.8 you can use this chained syntax as well:

$this->addColumn('contacts', 'email', $this->string(64)->after('id'));
like image 86
Zlatan Omerović Avatar answered Oct 11 '22 02:10

Zlatan Omerović