概述
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type Product struct {
ID uint `gorm:"primary_key"`
Code string
Price uint
}
func main() {
db,err := gorm.Open("mysql","root:root@tcp(localhost:3306)/gorm")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
// 自动迁移表,生成的表名为 products
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "L1212", Price: 1000})
// Read
var product Product
db.First(&product, 1) // find product with id 1
db.First(&product, "code = ?", "L1212") // find product with code l1212
// Update
db.Model(&product).Update("Price", 2000)
//Delete
db.Delete(&product)
}
模型定义
修改表名
type Product struct {
ID uint
Code string
Price uint
}
//修改默认表名
func (Product) TableName() string {
return "product2"
}
type Email struct {
ID int
Email string
}
func main() {
db, err := gorm.Open("mysql", "root:root@tcp(localhost:3306)/gorm")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
//设置默认表名前缀
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return "prefix_" + defaultTableName
}
//自动生成表
db.AutoMigrate(&Product{}, &Email{})
}
设置字段
type Product struct {
ID uint `gorm:"primary_key:id"`
Num int `gorm:"AUTO_INCREMENT:number"`
Code string
Price uint
Tag []Tag `gorm:"many2many:tag;"`
Date time.Time `gorm:"-"`
}
type Email struct {
ID int `gorm:"primary_key:id"`
UserID int `gorm:"not null;index"`
Email string `gorm:"type:varchar(100);unique_index"`
Subscribed bool
}
type Tag struct {
Name string
}
func main() {
db, err := gorm.Open("mysql", "root:root@tcp(localhost:3306)/gorm")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return "demo_" + defaultTableName
}
db.AutoMigrate(&Product{}, &Email{})
}
设置外键字段
type Profile struct {
gorm.Model
Refer int
Name string
}
type User struct {
gorm.Model
Profile Profile `gorm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"`
ProfileID int
}
增删改查
增
有疑问加站长微信联系(非本文作者)