1.
//GET请求 db操作,按id查询数据
r.GET("/getByIdDb", controller.GetUserById)
//GET请求 db操作,查询数据
r.GET("/getByUserList", controller.GetByUserList)
2.
//getByUserId
func GetUserById(context *gin.Context) {
user := &User{}
context.BindJSON(&user)
viewUser := dao.GetUserById(user.UserId)
ReturnSucess(context, 200, "查询成功", viewUser, 1)
}
func GetByUserList(context *gin.Context) {
list := dao.GetUserByList()
i := len(list)
fmt.Print(i)
ReturnSucess(context, 200, "查询成功", list, int64(len(list)))
}
3.
func GetUserById(id int) User {
var user User
err := config.DB.Where("user_id = ?", id).First(&user).Error
if err != nil {
log.Println("查询用户失败,原因:", err)
}
return user
}
func GetUserByList() []*User {
//申明一个数组
var userList []*User
err := config.DB.Find(&userList).Error
//err := config.DB.Where("1 = ?", 1).Statement.Error
if err != nil {
log.Println("查询用户失败,原因:", err)
}
return userList
}
4.测试