gorm自动创建表

473 阅读1分钟

前言

gorm可以在程序中控制建表,不用手动去创建数据库表

gorm自动建表操作

创建表

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "log"
    "time"
)

type User struct {
    Id          int64     `gorm:"primary_key;type:bigint(20);not null;column:id;comment:'主键id';" json:"id"`
    UserName    string    `gorm:"column:userName"`
    Sex         int       `gorm:"column:sex"`
    CreateTime  time.Time `gorm:"column:create_time;datetime(3);autoUpdateTime" json:"createTime"` // 创建时间
    UpdatedTime time.Time `gorm:"column:update_time;datetime(3);autoUpdateTime" json:"updateTime"` // 更新时间
}

func main() {
    dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    if err != nil {
       log.Println("连接数据库错误:", err)
       return
    }
    isExists := db.Migrator().HasTable(&User{})
    if isExists {
       log.Println("表存在")
    } else {
       err2 := db.Migrator().CreateTable(&User{})
       if err2 != nil {
          log.Println("创建表异常", err2)
          return
       }
    }
    log.Println("==========创建成功")
}

这时候,数据库就会多出一个users表

image.png

创建表注意

gorm创建表时,默认会加s,如上面创建一个user表,会出现users表,如果想去掉s,可以这么配置

db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
    NamingStrategy: schema.NamingStrategy{
       SingularTable: true, // 使用单数表名
    },
})

package main

import (
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/schema"
    "log"
    "time"
)

type User struct {
    Id          int64     `gorm:"primary_key;type:bigint(20);not null;column:id;comment:'主键id';" json:"id"`
    UserName    string    `gorm:"column:userName"`
    Sex         int       `gorm:"column:sex"`
    CreateTime  time.Time `gorm:"column:create_time;datetime(3);autoUpdateTime" json:"createTime"` // 创建时间
    UpdatedTime time.Time `gorm:"column:update_time;datetime(3);autoUpdateTime" json:"updateTime"` // 更新时间
}

func main() {
    dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
       NamingStrategy: schema.NamingStrategy{
          SingularTable: true, // 使用单数表名
       },
    })
    if err != nil {
       log.Println("连接数据库错误:", err)
       return
    }
    isExists := db.Migrator().HasTable(&User{})
    if isExists {
       log.Println("表存在")
    } else {
       err2 := db.Migrator().CreateTable(&User{})
       if err2 != nil {
          log.Println("创建表异常", err2)
          return
       }
    }
    log.Println("==========创建成功")
}

image.png

判断表是否存在

db.Migrator().HasTable(&User{})

删除表

db.Migrator().DropTable(&User{})

或者

db.Migrator().DropTable("users")

添加索引

db.Migrator().CreateIndex(&User{}, "Name")

修改索引名

db.Migrator().RenameIndex(&User{}, "Name", "hello")