2016-02-13 62 views
9

比方說,我有這樣的表結構:如何在表格中的特定位置添加Yii 2遷移的新列?

+----+------------+-----------+---------+------+---------+---------+---------------------+---------------------+ 
| 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 | 
+----+------------+-----------+---------+------+---------+---------+---------------------+---------------------+ 

而且我想添加一個名爲email新列,只是idfirst_name前使用的Migration類的addColumnmethod

只有我可以在我的新移民做的一件事是:

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

它將把它放在表的末尾,後updated場。

如何我可以在我的表內的特定位置添加一列,所以這個SQL查詢可以得到尊重:

ALTER TABLE contacts ADD email VARCHAR(64) AFTER id 

回答

17

解決它。如果任何人面臨同樣的問題,這是我使用的解決方案:

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

編輯:Yii 2.0.8版本,你可以使用這個鏈接的語法以及:

$this->addColumn('contacts', 'email', $this->string(64)->after('id')); 
7
public function up() 
{ 
    $this->addColumn('contacts', 'email', $this->string(64)->after('id')); 
} 
+3

請儘量避免將代碼轉儲爲答案,並嘗試解釋它的作用和原因 - 這樣一來,新用戶就可以更容易地從答案中學習。 – Frits

+2

另外,請注意哪個版本是''後''方法可用。 (從2.0.8:http://www.yiiframework.com/news/97/yii-2-0-8-is-released/) – omerowitz

2

您可以使用如下的遷移命令:

php yii migrate/create add_email_column_to_contacts_table --fields="email:string(64):after('id')" 
相關問題