// gormdb, _ := gorm.Open(mysql.Open("root:@(127.0.0.1:3306)/demo?charset=utf8mb4&parseTime=True&loc=Local")) g.UseDB(gormdb) // reuse your gorm db
// Generate basic type-safe DAO API for struct `model.User` following conventions
g.ApplyBasic( // Generate struct `User` based on table `users` g.GenerateModel("users"),
// Generate struct `Employee` based on table `users` g.GenerateModelAs("users", "Employee"),
// Generate struct `User` based on table `users` and generating options g.GenerateModel("users", gen.FieldIgnore("address"), gen.FieldType("id", "int64")),
// Generate struct `Customer` based on table `customer` and generating options // customer table may have a tags column, it can be JSON type, gorm/gen tool can generate for your JSON data type g.GenerateModel("customer", gen.FieldType("tags", "datatypes.JSON")),
) g.ApplyBasic( // Generate structs from all tables of current database g.GenerateAllTable()..., ) // Generate the code g.Execute() }
模板方法
当从数据库生成结构时,您也可以通过面的方式,给生成的model添加模板方法,例如:
type CommonMethod struct { ID int32 Name *string }
func(m *CommonMethod) IsEmpty() bool { if m == nil { returntrue } return m.ID == 0 }
func(m *CommonMethod) GetName() string { if m == nil || m.Name == nil { return"" } return *m.Name }
// WithModelNameStrategy 指定 model 结构名命名策略, 仅在从数据库同步表时工作 // If an empty string is returned, the table will be ignored WithModelNameStrategy(ns func(tableName string) (modelName string))
// WithOpts 指定全局 model 选项 WithOpts(opts ...ModelOpt)
Ignore Table
By WithTableNameStrategy, you can ignore some tables that do not need to be generated, such as tables starting with _.
g.WithTableNameStrategy(func(tableName string) (targetTableName string) { if strings.HasPrefix(tableName, "_") { //Just return an empty string and the table will be ignored. return"" } return tableName })
数据类型映射
指定model属性类型和 db 字段类型之间的映射关系。
var dataMap = map[string]func(gorm.ColumnType) (dataType string){ // int mapping "int": func(columnType gorm.ColumnType) (dataType string) { if n, ok := columnType.Nullable(); ok && n { return"*int32" } return"int32" },