38

I want to add a column at the seventh place in the table, I am using

$this->addColumn('table_name','column_name','type'); 

adds the column at the end. Is there any way where I can mention the place to add column? Or any after column keyword to add my new column after, for exapmle, password column. I have learnt aboout migration from Yii Doc

niac
  • 33
  • 2
  • 17
dibs_ab
  • 723
  • 2
  • 13
  • 24

2 Answers2

52
$this->addColumn('{{%user}}', 'username', 
            $this->string()->notNull()->unique()->after('id')
            );
gvanto
  • 1,936
  • 3
  • 21
  • 26
45

This should work!

$this->addColumn('table_name', 'column_name', 'type AFTER column6'); 

examples:

$this->addColumn('tbl_posts', 'email', 'VARCHAR(150) AFTER `name` ');
$this->addColumn('tbl_posts', 'phone', 'string AFTER `email` ');
SuVeRa
  • 2,784
  • 2
  • 20
  • 27
  • 1
    Thanks! It did :) I couldn't find the way to do it in the doc, is there anything else that you refer for Yii. and just one last question, when the name of migration class appears to be m120920_041119_update_users_about can I add $this->addColumn('users','about_ME','string AFTER password'); The _ME has to be in the name of the class? – dibs_ab Sep 20 '12 at 06:21
  • It works, but it works tricking; when Yii compose the SQL, it simply 'copy and past' the 'type' value into sql, and, casually, the syntax 'type AFTER a_column' generate valid SQL. Of course, I'm happy to use from now, and thanks for showing us this method. – realtebo Jan 23 '14 at 16:57
  • 2
    A lot of stuff is made by "tricking" in Yii (and PHP (and programming (and life)))'s world. – Meetai.com Dec 31 '14 at 02:24
  • 1
    BEFORE doesn't work since it's not available on mysql. It's FIRST, or AFTER. I don't know with other rdbms. – Prabowo Murti Oct 11 '15 at 16:32
  • 3
    this *IS NOT* the way it should be. use: $this->addColumn('{{%user}}', 'username', $this->string()->notNull()->unique()->after('id') ); as it was said by @gvanto – christian Sep 26 '17 at 20:20