Yii2 PostgreSQL迁移:新增列设另一列为默认值并加唯一索引
Yii2迁移实现PostgreSQL新增非空列并添加唯一索引
当然可以通过Yii2迁移完成这个需求,需要注意PostgreSQL的特性:无法直接给新增列设置基于其他列的动态默认值,所以得拆分步骤实现,具体代码如下:
1. 创建迁移文件
先通过控制台命令生成迁移类:
yii migrate/create add_unique_non_null_column_to_your_table
2. 编写迁移逻辑
打开生成的迁移文件,修改up()和down()方法:
use yii\db\Migration; class m240520_123456_add_unique_non_null_column_to_your_table extends Migration { // 替换为你的实际表名 private $tableName = 'your_table_name'; // 替换为你要新增的列名 private $newColumn = 'new_col'; public function up() { // 第一步:新增允许为空的列(先不设非空,避免数据填充问题) $this->addColumn($this->tableName, $this->newColumn, $this->string()->null()); // 第二步:将新列的值批量更新为col3的值 $this->execute("UPDATE {$this->tableName} SET {$this->newColumn} = col3"); // 第三步:修改新列,添加非空约束 $this->alterColumn($this->tableName, $this->newColumn, $this->string()->notNull()); // 第四步:给新列添加唯一索引(最后一个true参数表示唯一) $this->createIndex( "idx-{$this->tableName}-{$this->newColumn}", $this->tableName, $this->newColumn, true ); } public function down() { // 回滚时先删索引,再删列 $this->dropIndex("idx-{$this->tableName}-{$this->newColumn}", $this->tableName); $this->dropColumn($this->tableName, $this->newColumn); return true; } }
注意事项
- 替换代码中的
your_table_name为实际表名,new_col为你要新增的列名 - 列类型(
$this->string())请根据col3的实际类型调整,比如整数用$this->integer(),时间用$this->datetime()等 - 如果你的表数据量极大,批量更新可能耗时较长,建议在低峰期执行迁移
内容的提问来源于stack exchange,提问作者Karlis Pokkers
相关产品推荐
相关产品推荐

