使用 yii2 迁移从列中删除 UNIQUE

Remove UNIQUE from column using yii2 migrations

我有一个唯一的列,如何使用迁移从该列中删除 UNIQUE 键。

我正在使用最新版本的 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());
}

这样改变列是行不通的

因为 sql 创建唯一索引是这样的

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

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

只需使用 dropIndex() 并删除唯一索引。

我刚刚用 user table 上的 username 列对其进行了测试,因为我没有 email 列并且它按预期工作。在我的例子中,用户名列是唯一的,因此 migration/up 删除索引并再次添加索引。

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