### 讨论
为什么使用迁移文件来创建数据库?
1. 对数据库的变更操作有日志记录。
2. 便于生成一对多和多对多结构的数据库。
### 新建数据库
>[info] 请参考 http://www.yiiframework.com/doc-2.0/guide-db-migrations.html
1. 编写数据库迁移文件
2. 应用迁移文件,创建数据库
3. 生成Model
### 案例:Restaurant & Review
~~~
# 添加Restaurant表
yii migrate/create create_restaurant
$this->createTable('restaurant', [
'id' => $this->primaryKey(),
'name' => $this->string(),
'city' => $this->string(),
'province' => $this->string()
]);
yii migrate
# 添加Review表
yii migrate/create create_review
$this->createTable('review', [
'id' => $this->primaryKey(),
'rating' => $this->integer(),
'body' => $this->text()
]);
$this->addColumn('review', 'restaurant_id', $this->integer());
$this->createIndex('idx-review-restaurant_id', 'review', 'restaurant_id');
$this->addForeignKey('fk-review-restaurant_id', 'review', 'restaurant_id', 'restaurant', 'id', 'CASCADE');
yii migrate
# 生成Model
yii gii/model --tableName=restaurant --modelClass=Restaurant --ns=common\models
yii gii/model --tableName=review --modelClass=Review --ns=common\models
~~~
### 添加初始数据
1. 通过phpMyAdmin
2. 通过程序方式
~~~
yii migrate/create seed_restaurant_review
$restaurant = new Restaurant();
$restaurant->name = "老乡鸡";
$restaurant->city = '合肥';
$restaurant->province = '安徽省';
$restaurant->save();
$review = new Review();
$review->rating = 9;
$review->body = '真是美味的快餐';
$review->restaurant_id = $restaurant->id;
$review->save();
$review = new Review();
$review->rating = 6;
$review->body = '随便吃吃';
$review->restaurant_id = $restaurant->id;
$review->save();
yii migrate
~~~
### 添加字段
~~~
yii migrate/create add_reviewer_to_review --fields="reviewer_name:string"
$this->addColumn('review', 'reviewer_name', $this->string());
yii migrate
~~~
### 修改字段
~~~
yii migrate/create alter_reviewer_to_review
$this->alterColumn('review', 'reviewer_name', $this->string(100));
yii migrate
~~~