数据迁移的目前在开发数据库驱动应用程序的过程中,源代码转成数据库结构,用于跟踪数据库更改。
数据库迁移命令行工具 yii migrate
的作用在于:
- 创建新的迁移
- 恢复迁移
- 应用迁移
- 重新申请迁移
- 显示迁移状态
- 显示迁移记录
1.创建迁移
创建user表的数据迁移文件yii migrate/create init
新建的迁移文件位于/console/migrations/
数据迁移文件命名方式为m<YYMMDD_HHMMSS>_<Name>
例如:m130524_201442_init.php
当升级数据库时up()
被调用,当降级时down()
被调用。使用up()
创建新表,使用down()
删除表。
<?php
use yii\db\Migration;
class m130524_201442_init extends Migration
{
const TBLNAME = '{{%user}}';
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable(self::TBLNAME, [
'id' => $this->primaryKey(),
'username' => $this->string()->notNull()->unique(),
'auth_key' => $this->string(32)->notNull(),
'password_hash' => $this->string()->notNull(),
'password_reset_token' => $this->string()->unique(),
'email' => $this->string()->notNull()->unique(),
'status' => $this->smallInteger()->notNull()->defaultValue(10),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
], $tableOptions);
}
public function down()
{
$this->dropTable(self::TBLNAME);
}
}
2.数据迁移常用操作
升级数据库yii migrate
指定特定迁移yii migrate/to 130524_201442
恢复迁移yii migrate/down
恢复后重新迁移yii migrate/redo
3.数据迁移查看命令
查看新迁移,默认10个。yii migrate/new
yii migrate/new 5
yii migrate/new all
查看迁移历史记录,默认最近10个。yii migrate/history
yii migrate/history 5
yii migrate/history all
4.迁移中的事务处理
当执行数据迁移时,重要的是要确保每个迁移成功或失败。
建议在数据库操作中实用事务处理,要实现事务迁移,需将迁移代码放在safeUp()
和safeDown()
中。
若方法中任何操作失败,当前操作将被回滚。
5.数据迁移数据库操作
execute()
执行原始sql
createTable()
创建表renameTable()
重命名表dropTable()
删除表truncateTable()
清空表
insert()
插入单行batchInsert()
插入多行update()
更新行delete()
删除行
addColumn()
添加列renameColumn()
重命名列dropColumn()
删除列alterColumn()
修改列
createIndex()
创建索引dropIndex()
删除索引
addPrimaryKey()
添加主键dropPrimaryKey()
删除主键
addForeignKey()
添加外键dropForeignKey()
删除外键