addColumn yii migration position

25,143

Solution 1

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` ');

Solution 2

$this->addColumn('{{%user}}', 'username', 
            $this->string()->notNull()->unique()->after('id')
            );
Share:
25,143
dibs_ab
Author by

dibs_ab

Updated on October 03, 2022

Comments

  • dibs_ab
    dibs_ab over 1 year

    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

  • dibs_ab
    dibs_ab over 11 years
    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?
  • realtebo
    realtebo over 10 years
    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.
  • Meetai.com
    Meetai.com over 9 years
    A lot of stuff is made by "tricking" in Yii (and PHP (and programming (and life)))'s world.
  • Prabowo Murti
    Prabowo Murti over 8 years
    BEFORE doesn't work since it's not available on mysql. It's FIRST, or AFTER. I don't know with other rdbms.
  • christian
    christian over 6 years
    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
    christian over 6 years
    THIS is the way it should be.
  • ns16
    ns16 about 2 years
    Note that after method only support MySQL, Oracle and Cubrid.