YII2 MIGRATION的概念和使用详解

作者:袖梨 2022-06-25

首先,我们为什么需要migrations呢?

很久以来,PHP一直没有一种机制把项目最新的DB结构同时同步到不同的机器上.

很多时候我们是卸掉原来的DB结构再把最新的DB结构导进来.

如果某人修改了数据库结构,那么我们不得不把修改的SQL文件在所有不同的机器上跑一遍.而且这个修改者可能要一个一个得通知到所有人(实际情况可能要好点).


现在YII提供了一个管理我们DB结构的方法.我们不需要浪费时间和精力来维护我们的DB结构了.

以下是在开发过程中使用migrations的步骤:

安装好yii2后,Windows下运行cmd命令行,到yii2所在目录,输入以下命令,可以执行migration命令初始化数据表的程序,自动创建表:

代码如下 复制代码

D:xampphtdocsyii2>yii migrate
Yii Migration Tool (based on Yii v2.0.6)

Creating migration history table "migration"...Done.
Total 1 new migration to be applied:
m130524_201442_init

Apply the above migration? (yes|no) [no]:yes
*** applying m130524_201442_init
> create table {{%user}} ... done (time: 0.296s)
*** applied m130524_201442_init (time: 0.356s)


Migrated up successfully.


这个名为m130524_201442_init的migration定义在console/migrations/m130524_201442_init.php:

代码如下 复制代码

class m130524_201442_init extends Migration
{
public function up()
{
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://s*tac*ko*verflow.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}}');
}
}

通过这种方式创建migration,以后可以很方便的部署数据库

相关文章

精彩推荐