YII2 数据迁移

数据迁移的目前在开发数据库驱动应用程序的过程中,源代码转成数据库结构,用于跟踪数据库更改。

数据库迁移命令行工具 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() 删除外键

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值