gen
gen copied to clipboard
从mysql已有的表中生成model时不会生成长度限制么
从mysql已有的表中生成model时不会生成长度限制么
例如有个表 t_vcenters,其中venter_ip和user_name字段都是char(60),且vcenter_ip创建了索引,但是使用gen生成的话都是longtext类型,这样无法在对应字段应用索引 生成的model如下:
package model
const TableNameTVcenter = "t_vcenters"
// TVcenter mapped from table <t_vcenters>
type TVcenter struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true;comment:编号" json:"id"` // 编号
VcenterIP string `gorm:"column:vcenter_ip;comment:vcenter IP地址" json:"vcenter_ip"` // vcenter IP地址
VcenterName string `gorm:"column:vcenter_name;comment:VC名称" json:"vcenter_name"` // VC名称
UserName string `gorm:"column:user_name;comment:登录用户" json:"user_name"` // 登录用户
UserPassword string `gorm:"column:user_password;comment:登录密码" json:"user_password"` // 登录密码
}
// TableName TVcenter's table name
func (*TVcenter) TableName() string {
return TableNameTVcenter
}
gen代码如下:
package main
// gorm gen configure
import (
"fmt"
"gin-web/v2/dal/model"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gen"
)
const MySQLDSN = "xxxxxx"
func connectDB(dsn string) *gorm.DB {
db, err := gorm.Open(mysql.Open(dsn))
if err != nil {
panic(fmt.Errorf("connect db fail: %w", err))
}
return db
}
func main() {
g := gen.NewGenerator(gen.Config{
OutPath: "../../dal/query",
Mode: gen.WithDefaultQuery | gen.WithQueryInterface,
})
g.UseDB(connectDB(MySQLDSN))
g.ApplyBasic(g.GenerateAllTable()...)
// 通过ApplyInterface添加为book表添加自定义方法
g.ApplyInterface(func(model.Querier) {}, g.GenerateModel("book"))
// 执行并生成代码
g.Execute()
}
@sunerpy 提供下你希望生成的model是什么样子吧?
type TVcenter struct { ID int32 `gorm:"column:id;primaryKey;autoIncrement:true;comment:编号" json:"id"` // 编号 VcenterIP string `gorm:"column:vcenter_ip;comment:vcenter IP地址" json:"vcenter_ip"` // vcenter IP地址 VcenterName string `gorm:"column:vcenter_name;comment:VC名称" json:"vcenter_name"` // VC名称 UserName string `gorm:"column:user_name;comment:登录用户" json:"user_name"` // 登录用户 UserPassword string `gorm:"column:user_password;comment:登录密码" json:"user_password"` // 登录密码 }
type TVcenter struct {
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true;comment:编号" json:"id"` // 编号
VcenterIP string `gorm:"column:vcenter_ip;type:char(20);comment:vcenter IP地址" json:"vcenter_ip"` // vcenter IP地址
VcenterName string `gorm:"column:vcenter_name;comment:VC名称" json:"vcenter_name"` // VC名称
UserName string `gorm:"column:user_name;type:char(60);comment:登录用户" json:"user_name"` // 登录用户
UserPassword string `gorm:"column:user_password;comment:登录密码" json:"user_password"` // 登录密码
}
就像上面这种只不过多了一个type字段,我看issue里面有的人提供的是包含type字段的,但是我没找到相关的使用方法