開發中經常會用到的方法小結:
1. ./yii migrate xxx_xx
在表中插入某字段 :
public function up()
{
$this->addColumn('{{application_service}}', 'auditor', 'INT(10) NOT NULL COMMENT "審覈人" AFTER `user_id`, CHANGE COLUMN `status` `status` tinyint(4) NOT NULL COMMENT "綁定狀態,0:解綁 1:綁定" AFTER `auditor`');
}
修改表中某字段:
public function up()
{
$this->alterColumn('{{cp_application_service_binding}}', 'status', 'SMALLINT(4) NOT NULL DEFAULT 0 COMMENT "綁定狀態,0:解綁 1:未綁定 2:審覈中 3:審覈通過 4:審覈拒絕 5:禁用"');
}
修改字段名:
public function up()
{
$this->renameColumn('{{pay_method}}','updata_time','update_time');
}
增加索引:
public function up()
{
$this->createIndex('created_at', "{{common_app_base}}", ['created_at'],true);
}
創建數據表:
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_general_ci ENGINE=InnoDB COMMENT="菜單表"';
}
$this->createTable('{{%wx_menu}}', [
'id' => $this->primaryKey(),
'parent_id' => $this->integer(11)->defaultValue(0)->comment('父級菜單id'),
'menu_name' => $this->string(100)->notNull()->comment('菜單名稱'),
'menu_type' => $this->string(100)->notNull()->comment('菜單類型(menu菜單,sub_menu子菜單)'),
'menu_action' => $this->string(100)->notNull()->comment('菜單鏈接'),
'menu_roles' => $this->string(100)->comment('角色'),
'menu_depth' => $this->smallInteger(1)->defaultValue(0)->comment('菜單深度'),
'menu_icon' => $this->text()->comment('ICON代碼:圖標'),
'menu_des' => $this->text()->comment('菜單簡介'),
'menu_order' => $this->smallInteger(1)->defaultValue(0)->comment('顯示順序'),
'menu_show' => $this->smallInteger(1)->defaultValue(0)->comment('是否顯示(0:顯示, 1:不顯示)'),
'created_at' => $this->integer(),
'updated_at' => $this->integer(),
], $tableOptions);
}
刪除某字段:
public function down()
{
$this->dropColumn('{{common_app_base}}', 'manager_id');
}
刪除某張表:
public function down()
{
$this->dropTable('{{%common_file_storage_item}}');
}
2. ./yii migrate 默認執行 ./yii migrate/up
./yii migrate/down 執行某些撤銷對錶的操作
./yii migratre/to (遷移文件名)執行某個指定的遷移文件
在創建數據表的過程中可以同時聲稱多張表,刪除多張表
執行過的遷移文件,會在數據庫的migration 中生成一條記錄,記錄此遷移文件已經執行過,下次將執行數據表中不存在的遷移文件
注意:
./yii migrate/down 此命令執行不只刪除了對數據庫的操作同時也會刪除migration數據表中的執行記錄
此篇博文基本上能滿足初步使用yii2數據庫遷移遇到的問題,對於項目中接觸到新的會持續更新