在advanced\console\migrations文件夹下有一个 m130524_201442_init.php 文件

db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }
        $this->createTable('`user`', [
            '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('`user`');
    }
}


用cmd命令行进入advanced目录 ( 该目录下有yii.bat )

执行命令,选yes(输入y)

Yii2如何用migrate快速建表_第1张图片

这样就在数据库中新建了一张表user和另一张表migration

wKioL1is9PDAmOo3AAA8tJAGOiU728.png-wh_50

其中migration表的内容大致如下,猜想这个version字段和每次执行命令时php文件的名字&文件里的class名有关,所以每次执行命令时需要改动文件名和文件里面的class名

Yii2如何用migrate快速建表_第2张图片


那么,现在新建一张blog表,包含id、title、content、create_time四个字段

 

  1. 先将该php文件复制备份, 再将该文件重命名为m330524_201442_init.php(随机数字,只要和已有的version不同)

  2. 再将文件内的class m220524_201442_init extends Migration 中的 220524 改为 330524 (和文件名一样)

  3. 编辑字段内

db->driverName === 'mysql') {
          $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="文章表"';
        }
        $this->createTable('blog', [
            'id' => $this->primaryKey(),
            'title' => $this->string(100)->notNull()->defaultValue(''),
            'content' => $this->text(),
            'create_time' => $this->datetime(),
        ],$tableOptions);
    }
    public function down()
    {
        $this->dropTable('blog');
    }
}

最后执行命令,选yes

yii migrate console/migrations/m130524_201442_init.php

可以看到blog表建好了.