Files
rikako-note/Golang/gorm.md
2025-01-15 12:37:41 +08:00

2.6 KiB
Raw Blame History

GORM

QuickStart

GORM为golang的orm框架其使用示例如下

package main

import (
  "gorm.io/gorm"
  "gorm.io/driver/sqlite"
)

type Product struct {
  gorm.Model
  Code  string
  Price uint
}

func main() {
  db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
  if err != nil {
    panic("failed to connect database")
  }

  // Migrate the schema
  db.AutoMigrate(&Product{})

  // Create
  db.Create(&Product{Code: "D42", Price: 100})

  // Read
  var product Product
  db.First(&product, 1) // find product with integer primary key
  db.First(&product, "code = ?", "D42") // find product with code D42

  // Update - update product's price to 200
  db.Model(&product).Update("Price", 200)
  // Update - update multiple fields
  db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // non-zero fields
  db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

  // Delete - delete product
  db.Delete(&product, 1)
}

Declaring Models

gorm中Model通过struct来进行定义struct中的fields可以为如下类型

  • 基础golang类型
  • 指针
  • type alias
  • 自定义类型
    • 自定义类型需要实现database/sql中的Scanner和Valuer接口

如下为一个Model定义的示例

type User struct {
  ID           uint           // Standard field for the primary key
  Name         string         // A regular string field
  Email        *string        // A pointer to a string, allowing for null values
  Age          uint8          // An unsigned 8-bit integer
  Birthday     *time.Time     // A pointer to time.Time, can be null
  MemberNumber sql.NullString // Uses sql.NullString to handle nullable strings
  ActivatedAt  sql.NullTime   // Uses sql.NullTime for nullable time fields
  CreatedAt    time.Time      // Automatically managed by GORM for creation time
  UpdatedAt    time.Time      // Automatically managed by GORM for update time
  ignored      string         // fields that aren't exported are ignored
}

在上述Model中

  • 基础类型的字段可以直接访问,例如uint, uint8, string
  • 指针类型,例如*time.Time, *string等,代表该字段值可为空
  • sql/database中的sql.NullStringsql.NullTime类型,也代表该字段可为空
  • CreateAt字段和UpdatedAt字段是由Gorm管理的字段当Record被创建或更新时该字段的值会自动被注入为当前时间
  • Non-exported fields(首字母不是大写)并不会被映射