gorm模块学习记录

本文记录了使用GORM库进行Golang后端开发的过程,包括用go mod管理模块,数据库引擎创建,模型结构体定义,自动迁移,增删改查操作,关联查询,分组聚合及原生SQL执行等关键步骤。
摘要由CSDN通过智能技术生成

gorm

用 go mod 管理模块

  • 导包

    import (
    	"time"
    
    	"gorm.io/driver/mysql"
    	gorm "gorm.io/gorm"
    )
    
  • 创建数据库引擎

    db, err := gorm.Open(mysql.Open(MYSQL_URL))
    if err != nil {
         
        fmt.Println(err)
    }
    
  • 定义模型结构体

    // column 字段名
    // type   字段类型  bool、int、uint、float、string、time、bytes
    // scale ,size  字段长度  size貌似不起作用
    // default   默认值
    // primaryKey 主键
    // index ,uniqueIndex   索引,唯一索引
    // unique   唯一约束
    // not null  非空约束
    // check     检查
    // autoIncrement  自增长   autoIncrementIncrement 自增长的步长
    // embedded    嵌套   embeddedPrefix  嵌套前缀
    // autoCreateTime   自动生成创建时间如果增操作没有传值
    // autoUpdateTime   自动生成更新时间如果更新操作没有传值
    // comment          备注信息
    type Class struct {
         
    	ID        uint64    `gorm:"Primarykey;autoIncrement"`
    	Name      string    `gorm:"column:my_name;Type:string;scale:100"`
    	CreatedAt time.Time // CreatedAt 会在创建时如果是空会自动创建当前时间
    	UpdatedAt time.Time `gorm:"autoCreateTime;autoUpdateTime"` // 更新也一样
    	Flag      bool      `gorm:"type:bool;default:1"` // bool在数据库是0或1
    }
    
    type Student struct {
         
    	gorm.Model    // 嵌套gorm定义的基类
    	Name string
    	Age  uint8
    	C_id uint64
    }
    
    // gorm提供了四种验证钩子函数
    func (s *Student) BeforeCreate(tx *gorm.DB) error {
         
    	if s.Age <= 18 {
         
    		return errors.New("Student.BeforeCreate")
    	}
    	return nil
    }
    
  • 设置自动迁移

    db.AutoMigrate(&Class{
         })
    db.AutoMigrate(&Student{
         })
    
  • // 相当于修改了结构体,数据库中会自动更新
    c1 := &Class{
         
        Name: "一年级一班",
    }
    db.Create(c1)
    db.Create(&Class{
         
        Name: "一年级二班",
    })
    
    // 指定字段新增  指定的字段是结构体重的字段,不是数据库的
    db.Select("Name").Create(&Class{
         Name: "三年二班"})
    // 忽略指定字段新增  忽略的字段就算是定义了也会忽略
    db.Omit("ID").Create(&Class{
         Name: "三年三班", ID: 100})
    // 批量插入
    users := make([]Student, 100)
    for i := 0; i < 100; i++ {
         
        users[i] = Student{
         Name: fmt.Sprintf("user_%d", i)<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值