我有一个唯一的列,如何使用迁移从该列中删除 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
表上的username
列对其进行了测试,因为我没有email
列并且它按预期工作。在我的情况下,用户名列是唯一的,因此迁移/向上删除了索引,向下再次添加了索引。
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 );
}