18

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
robsch
  • 9,358
  • 9
  • 63
  • 104
Zlatan Omerović
  • 3,863
  • 4
  • 39
  • 67

4 Answers4

28

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'));
Zlatan Omerović
  • 3,863
  • 4
  • 39
  • 67
15
public function up()
{
    $this->addColumn('contacts', 'email', $this->string(64)->after('id'));
}
nikosid
  • 161
  • 1
  • 3
  • 4
    Please try to avoid just dumping a code as an answer and try to explain what it does and why - this way it will be easier for a newer user to learn from your answer. – Frits Jun 30 '16 at 13:22
  • 2
    Also, note from which version is the `after` method available. (From 2.0.8: http://www.yiiframework.com/news/97/yii-2-0-8-is-released/) – Zlatan Omerović Jun 30 '16 at 14:36
9

You can use migration command for that as below :

php yii migrate/create add_email_column_to_contacts_table --fields="email:string(64):after('id')"
Ravindra Bhalothia
  • 1,720
  • 2
  • 13
  • 16
0

If the migration name is of the form add_xxx_column_to_yyy_table then the file content would contain addColumn and dropColumn statements necessary.

So you should run the following command to add column email to table contacts:

php yii migrate/create add_email_column_to_contacts_table --fields="email:string(64)"

Documentation: https://www.yiiframework.com/doc/guide/2.0/en/db-migrations#add-column

Raja Bilal
  • 87
  • 1
  • 12