Getting Started
Overview
登录后可跨设备保存划线和私人笔记登录
The fantastic ORM library for Golang aims to be developer friendly.
Overview
- Full-Featured ORM
- Associations (Has One, Has Many, Belongs To, Many To Many, Polymorphism, Single-table inheritance)
- Hooks (Before/After Create/Save/Update/Delete/Find)
- Eager loading with
Preload,Joins - Transactions, Nested Transactions, Save Point, RollbackTo to Saved Point
- Context, Prepared Statement Mode, DryRun Mode
- Batch Insert, FindInBatches, Find/Create with Map, CRUD with SQL Expr and Context Valuer
- SQL Builder, Upsert, Locking, Optimizer/Index/Comment Hints, Named Argument, SubQuery
- Composite Primary Key, Indexes, Constraints
- Auto Migrations
- Logger
- Generics API for type-safe queries and operations
- Extendable, flexible plugin API: Database Resolver (multiple databases, read/write splitting) / Prometheus…
- Every feature comes with tests
- Developer Friendly
Install
go get -u gorm.io/gorm
go get -u gorm.io/driver/sqliteQuick Start
Generics API (>= v1.30.0)
package main
import (
"context"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
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")
}
ctx := context.Background()
db.AutoMigrate(&Product{})
err = gorm.G[Product](db).Create(ctx, &Product{Code: "D42", Price: 100})
product, err := gorm.G[Product](db).Where("id = ?", 1).First(ctx)
products, err := gorm.G[Product](db).Where("code = ?", "D42").Find(ctx)
err = gorm.G[Product](db).Where("id = ?", product.ID).Update(ctx, "Price", 200)
err = gorm.G[Product](db).Where("id = ?", product.ID).Updates(ctx, Product{Code: "D42", Price: 100})
err = gorm.G[Product](db).Where("id = ?", product.ID).Delete(ctx)
}Traditional API
package main
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
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")
}
db.AutoMigrate(&Product{})
db.Create(&Product{Code: "D42", Price: 100})
var product Product
db.First(&product, 1)
db.First(&product, "code = ?", "D42")
db.Model(&product).Update("Price", 200)
db.Model(&product).Updates(Product{Price: 200, Code: "F42"})
db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})
db.Delete(&product, 1)
}评论
登录后参与评论
正在加载评论…
InfoSphere