想要在go-zero中使用数据库,我们需要使用goctl model生成相关代码,然后在logics里面进行调用,下面就演示一下全过程
需要注意,在使用数据库日期的过程中,后面有一些选项可以选,有时候出现一些问题,可以去这里添加一些选项在这里查看,说不定可以解决,一般加上这几项
- charset=utf8mb4 :设置字符集
- parseTime=True :从数据库查出的
DATE和DATETIME将会转换成time.Time,而不是[]byte/string - loc=Local : 当使用parseTime时,会将时区改为本机的时区
root:123456.@tcp(mysql.fengsilin.pro:3306)/love_nest?charset=utf8mb4&parseTime=True&loc=Local1. 生成相关model代码
这个步骤就不写了,在另外一个地方写了
2.对conf和svc相关代码修改
go
package config
import (
"github.com/zeromicro/go-zero/rest"
)
type Config struct {
rest.RestConf
DB struct {
Datasource string
}
}在其中添加一个DB的配置,其中有一个datasource的配置,这个配置就填写着数据的连接地址,体现在配置里面就是这样的
yaml
Name: user-api
Host: 0.0.0.0
Port: 8888
DB:
datasource: root:123456.@tcp(mysql.fengsilin.pro:3306)/love_nest?charset=utf8mb4&parseTime=True&loc=Local在conf里面配置了这些之后,我们需要将相应的Model配置到context中去
go
package svc
import (
"github.com/zeromicro/go-zero/core/stores/sqlx"
"test-go-zero/love-nest/single/internal/config"
"test-go-zero/love-nest/single/model/users"
)
type ServiceContext struct {
Config config.Config
UserModel users.UsersModel
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
// 使用NewUsersModel新建一个UserModel,然后使用sqlx.NewMysql新建连接
UserModel: users.NewUsersModel(sqlx.NewMysql(c.DB.Datasource)),
}
}这里的context会伴随着整个项目,把这个Model添加到context中之后,就可以在logic中进行调用,不仅仅这个,还可以其他的客户端放入这里,比如操作redis的,都可以放到这里,需要注意的是,这里的使用的sqlx.NewMysql是因为这里的NewUsersModel方法需要的是sqlx.SqlConn,这里才填入的
3.编写具体代码
go
func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
resp = new(types.LoginResp)
if !(req.Email != "" && req.Password != "") {
resp.Msg = "密码或者邮箱为空"
resp.Code = 400
return
}
users, err := l.svcCtx.UserModel.Login(l.ctx, req.Email, req.Password)
fmt.Println(users)
if err == nil && users != nil {
resp.Msg = "登录成功"
resp.Code = 200
return
}
resp.Msg = "密码或者用户名错误"
resp.Code = 400
return
}这里就是根据context中的Model来对具体的方法进行调用