1、創建遷移文件
bee generate migration admins
在項目目錄下直接運行命令,它會默認在當前目錄下創建database/migrations目錄,然後生成對應的遷移文件。
2、通過遷移文件編寫數據表信息
package main
import (
"github.com/beego/beego/v2/client/orm/migration"
)
// DO NOT MODIFY
type Admin_20220116_002621 struct {
migration.Migration
}
// DO NOT MODIFY
func init() {
m := &Admin_20220116_002621{}
m.Created = "20220116_002621"
migration.Register("Admin_20220116_002621", m)
}
// Run the migrations
func (m *Admin_20220116_002621) Up() {
// use m.SQL("CREATE TABLE ...") to make schema update
m.CreateTable("admins", "innodb", "utf8mb4")
m.PriCol("id").SetAuto(true).SetDataType("int").SetUnsigned(true)
m.UniCol("userid", "user_id").SetDataType("int").SetNullable(false)
m.NewCol("is_super").SetDataType("tinyint").SetUnsigned(true).SetDefault("1")
m.NewCol("name").SetDataType("char(32)").SetDefault("''")
m.NewCol("created_at").SetDataType("datetime")
m.NewCol("updated_at").SetDataType("datetime")
m.SQL(m.GetSQL())
}
// Reverse the migrations
func (m *Admin_20220116_002621) Down() {
// use m.SQL("DROP TABLE ...") to reverse schema update
m.SQL("DROP TABLE IF EXISTS admins")
}
3、運行遷移文件
bee migrate -conn="root:@tcp(127.0.0.1:3306)/ddshop"
運行結果如下:
F:\go_course\shop\shopapi>bee migrate -conn="root:@tcp(127.0.0.1:3306)/ddshop"
______
| ___ \
| |_/ / ___ ___
| ___ \ / _ \ / _ \
| |_/ /| __/| __/
\____/ \___| \___| v2.0.2
2022/01/16 00:32:50 INFO ▶ 0001 Using 'mysql' as 'driver'
2022/01/16 00:32:50 INFO ▶ 0002 Using 'F:\go_course\shop\shopapi/database/migrations' as 'dir'
2022/01/16 00:32:50 INFO ▶ 0003 Running all outstanding migrations
2022/01/16 00:32:54 INFO ▶ 0004 |> 2022/01/16 00:32:52.524 [I] start upgrade Admin_20220116_002621
2022/01/16 00:32:54 INFO ▶ 0005 |> 2022/01/16 00:32:52.525 [I] exec sql: CREATE TABLE `admins` (
2022/01/16 00:32:54 INFO ▶ 0006 |> `id` int UNSIGNED auto_increment ,
2022/01/16 00:32:54 INFO ▶ 0007 |> `user_id` int NOT NULL ,
2022/01/16 00:32:54 INFO ▶ 0008 |> `is_super` tinyint UNSIGNED DEFAULT 1,
2022/01/16 00:32:54 INFO ▶ 0009 |> `name` char(32) DEFAULT '',
2022/01/16 00:32:54 INFO ▶ 0010 |> `created_at` datetime ,
2022/01/16 00:32:54 INFO ▶ 0011 |> `updated_at` datetime ,
2022/01/16 00:32:54 INFO ▶ 0012 |> PRIMARY KEY( `id`),
2022/01/16 00:32:54 INFO ▶ 0013 |> UNIQUE KEY `userid`( `user_id`))ENGINE=innodb DEFAULT CHARSET=utf8mb4;
2022/01/16 00:32:54 INFO ▶ 0014 |> 2022/01/16 00:32:52.548 [I] end upgrade: Admin_20220116_002621
2022/01/16 00:32:54 INFO ▶ 0015 |> 2022/01/16 00:32:52.548 [I] total success upgrade: 1 migration
2022/01/16 00:32:54 SUCCESS ▶ 0016 Migration successful!
運行結束後觀察一下數據庫是否有創建對應的遷移信息
4、修改字段
bee generate migration admin_modify_name_column
// Run the migrations
func (m *AdminModifyNameColumn_20220116_003615) Up() {
// use m.SQL("CREATE TABLE ...") to make schema update
m.AlterTable("admins")
m.RenameColumn("name", "name").SetDataType("char(32)").SetDefault("'admin'")
m.SQL(m.GetSQL())
}
5、添加字段
bee generate migration admin_add_role_column