# Yii数据库迁移
## 描述
在开发和维护一个数据库驱动的应用程序时,数据库的结构会随代码的改变而改变. Yii 提供了一个 数据库迁移功,该功能可以记录数据库的变化, 以便使数据库和源代码一起受版本控制.
Yii 提供了一整套的迁移命令行工具,通过这些工具你可以:
* 创建新的迁移
* 提交迁移
* 恢复迁移
* 重新提交迁移
* 现实迁移历史和状态
下面我简单用一下,至于更复杂的应用会在后期的更新中补充掉
## 实操
先看下帮助
~~~
$ cd thesaurus
$ php yii migrate -h
~~~
最重要的是下面这段
~~~
- migrate/create Creates a new migration.
- migrate/down Downgrades the application by reverting old migrations.
- migrate/history Displays the migration history.
- migrate/mark Modifies the migration history to the specified version.
- migrate/new Displays the un-applied new migrations.
- migrate/redo Redoes the last few migrations.
- migrate/to Upgrades or downgrades till the specified version.
- migrate/up (default) Upgrades the application by applying new migrations.
~~~
出于好奇心,我们先*create*一个表试试看看
~~~
$ php yii migrate/create create_terms_table
~~~
提示创建一个新的迁移文件,输入*yes*看到*New migration created successfully.*表示成功
生成的文件在*/thesaurus/console/migrations/mxxxxxx_xxxxxx_create_terms_table.php*,打开编辑terms所需字段
![](https://box.kancloud.cn/38d04f1df5e8735d86cedbd355ac706f_611x452.png)
我这里添加了*name*和*create_at*,*update_at*字段,上边的属性各位估计也能看明白,下边执行迁移
~~~
$ php yii migrate
~~~
安装提示输入*yes*,看到*Migrated up successfully*说明成功,通过数据库工具*Navicat Premium*可以看到数据库中多了三个表*migration*,*terms*,*user*,其中*migration*是用来记录迁移历史记录的,*user*是项目初始化中自带的(也就是你刚刚登陆不成功那个*user*表),*terms*当然使我们自己创建的
剩下的命令就不做过多演示了,记住几个比较常用,完全无压力
~~~
- migrate/create 创建新的迁移.
- migrate/down 恢复上一个迁移.
- migrate/history 显示迁移历史和状态.
- migrate 提交迁移
~~~