grom初使用|青训营笔记

222 阅读2分钟

这是我参与「第三届青训营 -后端场」笔记创作活动的第1篇笔记,用来记录一下使用到的gorm数据库操作。

//先导包
import (
   "gorm.io/driver/mysql"
   "gorm.io/gorm"
)

var _db *gorm.DB

func init() {
   var err error
   //连接设置,其中utf8mbr才是真正的utf-8,parseTime=True&loc=Local需要写,不然后面插入数据库的值有时间的时可能会出错
   dsn := "用户名:密码@tcp(127.0.0.1:3306)/mytiktok?charset=utf8mb4&parseTime=True&loc=Local"
   _db, err = gorm.Open(mysql.Open(dsn))
   if err != nil {
      panic("数据库连接错误,error=" + err.Error())
   }
   sqlDB, _ := _db.DB()

}
//定义获取连接的函数
func GetDB() *gorm.DB {
   return _db
}
复制代码

然后定义model 即定义对象,并使其值与数据库定义属性的名字一一对应


import "time"

type Comments struct {
   ID         int       `gorm:"column:id;primary_key"`
   VideoId    string    `gorm:"column:video_id"`
   UserId     int       `gorm:"column:user_id"`
   Content    string    `gorm:"column:content"`
   CreateDate time.Time `gorm:"column:create_date;type:datetime;"`
}
复制代码

特别注意的是加入时间哪里,我发现不仅要标注对应的列,后面还需要加上一个type:datetime;此外,还可以根据个人添加所需要的属性,比如非空值等

db := commom.GetDB()
//可以通过db使用各种各样的函数来查询,极大简化了程序员写数据库语句。grom有许多函数,需要的可以自己去看文档
db.Table("comments").Select("id").Find(&commentId)

复制代码

此外,在我做项目中遇到的较大的问题就是,需要通过comment中的userId补全user,然后将其变成真正的comment对象 于是,我用的笨方法,我是又创了一个user的model,通过userId在数据库里查询,并将查到的数据封装成model对象,再将它的值赋给comment对象

var userinfo model.Users
db.Table("users").Where("id=?", comment.UserId).Find(&userinfo)
commentCommon.User.Id = userinfo.ID
commentCommon.User.Name = userinfo.Username
commentCommon.User.FollowerCount = userinfo.FansCounts
commentCommon.User.FollowCount = userinfo.FollowCounts
commentCommon.User.IsFollow = false
commentCommon.CreateDate = comment.CreateDate.Format("2006.01.02 15:04:05")
commentCommon.Content = comment.Content
复制代码

end

利用gorm使用数据库,出错的话,不是特别容易排查,因为你不知道完整的MySQL语句,只有到调试时,控制台会显示,然后像我,开始对gorm函数的使用很不熟练,也不知道那些个函数能不能用,就是一直在调试,所以大家出错了不要慌,慢慢就熟悉了,而且常见的函数就那么几个。