[go] golang exercise item – addition, deletion, query and modification of Gorm and MySQL

Time:2021-10-1

The following code is placed in users.go under the models package

The table structure is consistent with the struct field. Change the underline of the table field into a hump named with capital letters

Create, find, delete and update users. See the following specific methods

 

package models

import (
    _ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
    Model
    Name string `json:"name"`
    Password string `json:"password"`
    Nickname string `json:"nickname"`
    Avator string `json:"avator"`
    RoleName string `json:"role_name"`
}
func CreateUser(name string,password string,avator string,nickname string){
    user:=&User{
        Name:name,
        Password: password,
        Avator:avator,
        Nickname: nickname,
    }
    DB.Create(user)
}
func UpdateUser(id string,name string,password string,avator string,nickname string){
    user:=&User{
        Name:name,
        Avator:avator,
        Nickname: nickname,
    }
    if password!=""{
        user.Password=password
    }
    DB.Model(&User{}).Where("id = ?",id).Update(user)
}
func FindUser(username string)User{
    var user User
    DB.Where("name = ?", username).First(&user)
    return user
}
func FindUserById(id interface{})User{
    var user User
    DB.Where("id = ?", id).First(&user)
    return user
}
func DeleteUserById(id string){
    DB.Where("id = ?",id).Delete(User{})
}
func FindUsers()[]User{
    var users []User
    DB.Order("id desc").Find(&users)
    return users
}
func FindUserRole(query interface{},id interface{})User{
    var user User
    DB.Select(query).Where("user.id = ?", id).Joins("join user_role on user.id=user_role.user_id").Joins("join role on user_role.role_id=role.id").First(&user)
    return user
}

 

Recommended Today

Less sass SCSS stylus of CSS preprocessor

Let’s ask ourselves a question: why do we need a preprocessor?The answer is self-evident, that is, CSS itself has some disadvantages: The syntax is not strong enough to be written nested, resulting in unclear style logic in the project. There is no variable and logical reuse mechanism. When it is necessary to reuse code, you […]