80 lines
2.6 KiB
Markdown
80 lines
2.6 KiB
Markdown
- [GORM](#gorm)
|
||
- [QuickStart](#quickstart)
|
||
- [Declaring Models](#declaring-models)
|
||
|
||
|
||
# GORM
|
||
## QuickStart
|
||
GORM为golang的orm框架,其使用示例如下:
|
||
```go
|
||
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定义的示例:
|
||
```go
|
||
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.NullString`和`sql.NullTime`类型,也代表该字段可为空
|
||
- `CreateAt`字段和`UpdatedAt`字段是由Gorm管理的字段,当Record被创建或更新时,该字段的值会自动被注入为当前时间
|
||
- `Non-exported fields`(首字母不是大写)并不会被映射
|
||
|