1.通过 yii migrate/create mytable 创建一个类似于 \my-yii-advanced-app\console\migrations\m150427_080248_mytable.php 的文件 内容如下:

(可以使用yii migrate --migrationPath=@yii/rbac/migrations/导入Yii官方提供的权限控制表)

<?php

use yii\db\Schema;
use yii\db\Migration;

class m150427_080248_mytable extends Migration
{
    public function up()
    {

      $tableOptions = null;
      if ($this->db->driverName === 'mysql') {
        $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
      }


      $this->createTable('{{%t_adm_user}}', [
        'id' => Schema::TYPE_PK,
        'username' => Schema::TYPE_STRING . '(64) NOT NULL',
        'password' => Schema::TYPE_STRING . '(64) NOT NULL',
        'userphoto' => Schema::TYPE_STRING . '(64) NOT NULL',
        ], $tableOptions);
      $pw1 = Yii::$app->security->generatePasswordHash('admin');
      $pw2 = Yii::$app->security->generatePasswordHash('demo');
      $sql = "INSERT INTO `t_adm_user` (`id`, `username`, `password`) VALUES
          (1, 'admin', '$pw1'),
          (2, 'demo', '$pw2');";
      $this->execute($sql);

    }

    public function down()
    {
        echo "m150427_080248_mytable cannot be reverted.\n";

        return false;
    }
    
    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }
    
    public function safeDown()
    {
    }
    */
}

2.可参考安装yii高级应用模版是自带的\my-yii-advanced-app\console\migrations\m130524_201442_init.php文件进行代码的填写

<?php

use yii\db\Schema;
use yii\db\Migration;

class m130524_201442_init extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->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' => Schema::TYPE_PK,
            'username' => Schema::TYPE_STRING . ' NOT NULL',
            'auth_key' => Schema::TYPE_STRING . '(32) NOT NULL',
            'password_hash' => Schema::TYPE_STRING . ' NOT NULL',
            'password_reset_token' => Schema::TYPE_STRING,
            'email' => Schema::TYPE_STRING . ' NOT NULL',

            'status' => Schema::TYPE_SMALLINT . ' NOT NULL DEFAULT 10',
            'created_at' => Schema::TYPE_INTEGER . ' NOT NULL',
            'updated_at' => Schema::TYPE_INTEGER . ' NOT NULL',
        ], $tableOptions);
    }

    public function down()
    {
        $this->dropTable('{{%user}}');
    }
}

对应的mysql字段类型可参考链接:http://www.yiiframework.com/doc-2.0/yii-db-schema.html

3.通过migrate文件生成数据表到数据库使用 yii migrate 命令(要先在配置文件中配置好数据库信息并创建相应的数据库)

由于mytest和mytable都为空,所以只创建了有内容的user表,查看数据库如图:

migration表内容如下:

posted on 2015-04-27 16:18  浊浊然  阅读(1754)  评论(0编辑  收藏  举报