Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove UNIQUE from column using yii2 migrations

I have a column that is unique, how do I remove the UNIQUE key from that column using migrations.

I am using the latest version of yii 2

public function up()
{
    $this->alterColumn('user', 'email', $this->string(255)->notNull());

}

public function down()
{
    $this->alterColumn('user', 'email', $this->string(255)->notNull()->unique());
}

Altering the column as such doesn't work

like image 270
user1724416 Avatar asked Feb 04 '16 14:02

user1724416


1 Answers

As the sql to create a Unique index is something like this

//sql to add a unqique index
ALTER TABLE `user` ADD UNIQUE (
`email`
);

//sql to remove a unqique index
ALTER TABLE 'user' DROP INDEX email;

just use dropIndex() and remove the unique index.

I just tested it with the username column on my user table because i didn't had a emailcolumn and it worked as expected. In my case the username column was unique therefore migration/up removed the index and down adds the index again.

public function up()
{
    // remove the unique index
    $this->dropIndex('username', 'user');
}

public function down()
{
    // add the unique index again
    $this->createIndex('username', 'user', 'username', $unique = true );
}
like image 113
BHoft Avatar answered Nov 11 '22 17:11

BHoft