Golang下的ORM框架-Gorm框架学习记录(3) | 青训营笔记

89 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 10 天

Gorm框架CURD接口

更新

为了读者阅读方便起见,我们先放出用户信息的数据结构

type UserInfo struct {
   UserID            int64  `gorm:"column:UserID" json:"id,omitempty"`                   // 用户id
   UserName          string `gorm:"column:Name"json:"name,omitempty"`                    // 用户名称
   UserFollowCount   int    `gorm:"column:FollowCount"json:"follow_count,omitempty"`     // 用户关注数
   UserFollowerCount int    `gorm:"column:FollowerCount"json:"follower_count,omitempty"` // 用户粉丝数
   IsFollow          bool   `gorm:"column:IsFollow"json:"is_follow,omitempty"`           // 是否关注
}

func (value UserInfo) TableName() string {
   return "UsersInfo"
}

保存所有字段

Gorm提供 Save 方法保存所有的字段,即使字段是零值

db.First(&userInfo) 
userInfo.UserName = "wy" 
userInfo.UserFollowCount = 100 
db.Save(&userInfo)
// 等价于
// UPDATE UsersInfo SET UserName='wy', UserFollowCount=100 WHERE UserID=1;

更新单个列

当使用 Update 更新单个列时,你需要指定条件,否则会返回 ErrMissingWhereClause 错误,查看 Block Global Updates 获取详情。

// 条件更新
db.Model(&UserInfo{}).Where("IsFollow = ?", true).Update("UserName", "ww")
// 等价于:UPDATE UsersInfo SET UserName='ww' WHERE IsFollow=true;

// UsersInfo 的 UserID 是 `1`
db.Model(&userInfo).Update("UserName", "ww")
// 等价于:UPDATE UsersInfo SET UserName='ww' WHERE UserID=111;

还有更新多列,更新选定字段等相关操作,由于我还没有学习掌握,大家可以看看这个链接进行深入学习 更新 | CRUD 接口 |《GORM 中文文档 v2》| Go 技术论坛 (learnku.com)

删除

删除一条记录

当我们使用Gorm Delete 方法删除一条记录时,删除对象需要指定主键,否则会触发 批量Delete

// userInfo 的 UserID 是 `10` 
db.Delete(&userInfo) 
// 等价于:DELETE from UsersInfo where UserID = 10;

// 带额外条件的删除
db.Where("UserName = ?", "wzh").Delete(&userInfo)
// 等价于:DELETE from UsersInfo where UserID = 10 AND UserName = "wzh";

根据主键删除

Gorm允许通过内联条件指定主键来检索对象,但只支持整型数值,因为string可能导致SQL注入问题。

db.Delete(&UserInfo{}, 10)
// 等价于:DELETE FROM UsersInfo WHERE UserID = 10;

db.Delete(&UserInfo{}, "10")
// 等价于:DELETE FROM UsersInfo WHERE UserID = 10;

db.Delete(&userInfo, []int{1,2,3})
// 等价于:DELETE FROM UsersInfo WHERE UserID IN (1,2,3);

批量删除

如果指定的值不包括主属性,那么 GORM 会执行批量删除,它将删除所有匹配的记录

db.Where("UserName LIKE ?", "%w%").Delete(UserInfo{})
// 等价于:DELETE from UsersInfo where UserName LIKE "%w%";

db.Delete(&UserInfo{}, "UserName LIKE ?", "%w%")
// 等价于:DELETE from UsersInfo where UserName LIKE "%w%";

参考引用:GORM中文文档《GORM 中文文档》 | Go 技术论坛 (learnku.com)