下面代码放在models包下的users.go中
表结构和struct字段是一致的,把表字段的下划线变成首字母大写的驼峰命名
package models import ( _ "github.com/jinzhu/gorm/dialects/MysqL" ) type User struct { Model Name string `json:name` Password password` Nickname nickname` Avator avator` RoleName role_name` } func createuser(name string,password string){ user:=&User{ Name:name,Password: password,Avator:avator,Nickname: nickname,} DB.Create(user) } func UpdateUser(id if password!=""{ user.Password=password } DB.Model(&User{}).Where(id = ?,id).Update(user) } func FindUser(username )User{ var user User DB.Where(name = ?",username).First(&user) return user } func FindUserById(id interface{})User{ irst(& user } func DeleteUserById(id ){ DB.Where( users []User DB.Order(id desc").Find(&users) users } func FindUserRole(query interface{},id user User DB.Select(query).Where(user.id = ?join user_role on user.id=user_role.user_id").Joins(join role on user_role.role_id=role.id").First(& user }