user1724416
user1724416

Reputation: 954

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

Upvotes: 7

Views: 8509

Answers (1)

BHoft
BHoft

Reputation: 1663

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 );
}

Upvotes: 8

Related Questions