[TOC]
### 創建遷移文件
> yii migrate/create <name>
~~~
./yii migrate/create create_test_table
~~~
> 會生成 /console/migrations/m200612_071636_create_test_table.php 遷移文件
### 修改遷移文件 (根據業務)
~~~
class m200612_071636_create_test_table extends Migration
{
/**
* {@inheritdoc}
*/
public function safeUp()
{
// 創建test表
$this->createTable('{{%test}}', [
'id' => $this->primaryKey()->notNull()->comment('ID'),
'title' => $this->string(100)->notNull()->comment('標題')->unique(),
'content' => $this->text(),
'view_num' => $this->integer()->unsigned()->notNull()->defaultValue(0)->comment('瀏覽量'),
'created_at' => $this->dateTime()->comment('創建時間'),
'updated_at' => $this->dateTime()->comment('更新時間'),
]);
// 新增字段
$this->addColumn('{{%test}}', 'user_name', $this->string(50)->unique()->comment('用戶')->after('content'));
$this->addColumn('{{%test}}', 'sex', $this->tinyInteger()->comment('性別(0未知/1男/2女)')->defaultValue(0)->after('user_name'));
// 給字段添加注釋
$this->addCommentOnColumn('{{%test}}', 'content', '內容');
// 修改字段
$this->alterColumn('{{%test}}', 'title', $this->string(300)->comment('標題x'));
$this->renameColumn('{{%test}}', 'title', 'title2');
// 新增索引
$this->createIndex('sex_index', '{{%test}}', ['sex'], true); // 唯一索引
$this->createIndex('sex_username_index', '{{%test}}', ['user_name', 'sex'], false); // 復合索引
// 插入一條test數據
$this->insert('{{%test}}', [
'id' => 1,
'title2' => 'haha',
'content' => 'haha from content',
'created_at' => '2017-09-08 12:33:42',
'updated_at' => '2017-09-08 13:34:47',
]);
}
/**
* {@inheritdoc}
* 該回滾方法可以為空,實際上如果執行了回滾的話,相當于也就執行空,migration表刪除對應記錄,并進行下一個回滾
*/
public function safeDown()
{
// 刪除索引
$this->dropIndex('sex_index', '{{%test}}');
$this->dropIndex('sex_username_index', '{{%test}}');
// 刪除字段
$this->dropColumn('{{%test}}', 'user_name');
$this->dropColumn('{{%test}}', 'sex');
//刪除一條數據
$this->delete('{{%test}}',[
'id' => 1
]);
$this->dropTable('{{%test}}');
}
}
~~~
### 遷移文件更新操作
~~~
# 更新遷移文件
# 會根據migration表里已更新的文件會自動排除,然后再根據剩下沒有更新的遷移文件全部執行
# 執行順序根據m200612_071636_create_test_table.php 里前面的數字從小到大執行
./yii migrate
# 回滾遷移文件,執行一次,回滾一個遷移文件,會從migration表刪除對應的一條記錄
./yii migrate/down
~~~
### 查看遷移歷史
> 可以通過指令列出提交或者未提交的遷移:
~~~
.\yii migrate/history #顯示最近10次提交的遷移
.\yii migrate/history 6 #顯示最近5次提交的遷移
.\yii migrate/history all #顯示所有的提交遷移
.\yii migrate/new #顯示最近10次未提交的遷移
.\yii migrate/new 6 #顯示最近6次未提交的遷移
.\yii migrate/new all #顯示所有的未提交遷移
~~~
- 基礎教程
- 入門安裝
- Yii2 composer 安裝慢解決
- Cookies
- 數據庫操作
- 數據提供者
- 助手類
- 驗證規則
- GridView
- DetailView
- YII2分頁
- JS、CSS的引用
- Excel導出
- 中文轉拼音
- 發送郵件
- 第三方插件
- Session跨域共享
- Url跨域訪問
- 場景應用
- 查詢條件鏈
- Session分布式共享
- Redis的使用
- mongodb
- 高級教程
- 自定義gii模板
- 角色權限管理(RBAC)
- user組件的配置
- 國際化(I18N)
- 小部件(Widget)
- 模塊(Module)
- 行為(Behavior)
- 緩存(Cache)
- migrate 數據庫遷移
- phpstorm
- 快捷鍵
- 自定義
- 其它插件