基本用法
package main
import (
"fmt"
"strings"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/spaolacci/murmur3"
)
type UserInfo struct {
ID uint
Name string
Gender string
Hobby string
}
type Like struct {
ID int `gorm:"primary_key"`
Ip string `gorm:"type:varchar(20);not null;index:ip_idx"`
Ua string `gorm:"type:varchar(256);not null;"`
Title string `gorm:"type:varchar(128);not null;index:title_idx"`
Hash uint64 `gorm:"unique_index:hash_idx;"`
CreatedAt time.Time
}
type Animal struct {
ID int `gorm:"primary_key"`
Name string `gorm:"type:varchar(256)`
}
func CreateAnimals(db *gorm.DB) err {
tx := db.Begin()
if err := tx.Create(&Animal{Name: "Giraffe"}).Error; err != nil {
tx.Rollback()
return err
}
if err := tx.Create(&Animal{Name: "Lion"}).Error; err != nil {
tx.Rollback()
return err
}
tx.Commit()
return nil
}
func main() {
db, err := gorm.Open("mysql", "root:123456@(127.0.0.1:3308)/gotest?charset=utf8mb4&parseTime=True&loc=Local")
if err != nil {
panic(err)
}
defer db.Close()
db.DB().SetConnMaxIdleTime(5)
db.DB().SetMaxOpenConns(100)
db.AutoMigrate(&UserInfo{})
u1 := UserInfo{1, "枯藤", "男", "篮球"}
u2 := UserInfo{4, "topgoer.com", "女", "足球"}
u3 := UserInfo{3, "zzd", "男", "台球"}
db.Create(&u1)
db.Create(&u2)
db.Create(&u3)
var u = new(UserInfo)
db.First(u)
var uu UserInfo
db.Find(&uu, "hobby=?", "足球")
fmt.Printf("%#v\n", uu)
db.Model(&uu).Update("hobby", "子色球")
db.Model(&uu).Updates(UserInfo{Name: "hell", Hobby: "乒乓求"})
db.Delete(&u)
if !db.HasTable(&Like{}) {
if err := db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").CreateTable(&Like{}).Error; err != nil {
panic(err)
}
}
var ip = "10.10.10.10"
var ua = "haha"
var title = "title"
like := &Like{
Ip: ip,
Ua: ua,
Title: title,
Hash: murmur3.Sum64([]byte(strings.Join([]string{ip, ua, title}, "-"))) >> 1,
CreatedAt: time.Now(),
}
if err := db.Create(like).Error; err != nil {
return
}
var count int
err2 := db.Model(&Like{}).Where(&Like{Ip: ip, Ua: ua, Title: title}).Count(&count).Error
if err2 != nil {
return
}
fmt.Println(count)
}
更新数据update 解决值为0时被忽略
values := map[string]uint{
"Status": status,
}
DB.Model(&User{}).Where(query, args...).Update(values)