gorm 各种操作


type User struct {
     
    Id            uint32  		`gorm:"column:id;primary_key" sql:"-"`
    Age   		 uint32  		`gorm:"column:age"`
    Name  		 string  		`gorm:"column:name"`
    CreatedAt     time.Time		`gorm:"column:created_at" sql:"-"`
    AddressList   []Address  	`gorm:"foreignkey:UserId;association_foreignkey:Id"`
}

type Address struct {
     
    Id      uint32  `gorm:"column:id;primary_key" sql:"-"`
    area    string  `gorm:"column:area"`
    UserId  uint32  `gorm:"column:user_id"`
}


// 查 
total := 0
list := make([]*User, 0)
page := 1
pageCount := 10
// 连表
query := db.Table("t_user a").Select("a.id, a.age").Joins("left join t_address i on i.user_id=a.id").Where("a.age = ? ", 18)
if id != 0 {
     
    query = query.Where("a.id != ?", id)
}
err := query.Count(&total).Find(&list).Error
// 关联
err := db.Model(&User{
     }).Count(&total).Error
err := db.Preload("AddressList").Offset((page - 1) * pageCount).Limit(pageCount).Order("created_at desc").Find(&list).Error


//增
data := &User{
     
    Age:  uint32(18),
    Name: "jin",
}
err := db.Create(data).Error


//删
err := db.Where("id = ?", id).Delete(User{
     }).Error


// 改
data := &User{
     
    Id:      id,
    Age: uint32(25),
}
err := db.Model(&User{
     }).Updates(data).Error

// 改0 或 "" 用map
data := make(map[string]interface{
     })
data["age"] = 20
err := db.Model(&User{
     }).Where("id = ?", id).Updates(data).Error

你可能感兴趣的:(go,gorm,golang)