1. 程式人生 > >19 Go的全能ORM簡單入門

19 Go的全能ORM簡單入門

name 內存 uri 結合 無法 查看 文檔 word 源碼

gorm

昨天我的ldap賬戶改了以後,openfalcon(v2.1)-dashboard竟然無法登陸了!顯然,沒有把我的密碼同步到本地數據庫裏面,怎麽辦?只能改openfalcon用戶認證的源碼了,把ldap密碼同步到數據庫裏面,在這裏改動的當中,發現openfalcon使用的gorm來操作數據庫,那麽我就簡單的了解下gorm作為低級入門了。

話不多說,我們先看下openfalcon用戶登錄這塊的源碼:

1. 導入包與定義結構體
import (
    "github.com/jinzhu/gorm"
)

type DBPool struct {
    Falcon    *gorm.DB
    Graph     *gorm.DB
    Uic       *gorm.DB
    Dashboard *gorm.DB
    Alarm     *gorm.DB
}
2. 定義變量
var db config.DBPool
3. http請求處理與使用orm操作數據庫
    password := utils.HashIt(inputs.Passwd)

    var user uic.User
    user = uic.User{
        Name:   inputs.Name,
        Passwd: password,
        Cnname: inputs.Cnname,
        Email:  inputs.Email,
        Phone:  inputs.Phone,
        IM:     inputs.IM,
        QQ:     inputs.QQ,
    }
    db.Uic.Table("user").Where("name = ?", inputs.Name).Scan(&user)
    
    // 以下代碼 針對剛才說的bug,我自己改過了的,
    if user.ID != 0 { //  update the user‘s person info
        //h.JSONR(c, http.StatusBadRequest, "name is already existing")
        dt := db.Uic.Table("user").Where("name = ?", inputs.Name).Update("passwd", password)
        if dt.Error != nil {
            h.JSONR(c, http.StatusBadRequest, dt.Error)
            return
        }
    } else { //
        //for create a root user during the first time
        if inputs.Name == "root" {
            user.Role = 2
        }

        dt := db.Uic.Table("user").Create(&user)
        if dt.Error != nil {
            h.JSONR(c, http.StatusBadRequest, dt.Error)
            return
        }
    }

上面的流程說明了,下面就結合openfalcon的源碼看看gorm的使用吧

gorm的簡單使用

查詢用戶信息

先提前定義好用戶信息的結構體,基本與mysql表字段一致

db.Uic.Table("user").Where("name = ?", inputs.Name).Scan(&user)

數據更新

  1. 更新一個字段用Update
  2. 更新多個字段用Updates
更新一個字段

更新一個字段可以直接寫Update(字段名,新值)

dt := db.Uic.Table("user").Where("name = ?" , inputs.Name).Update("passwd", password)
if dt.Error != nil {
    return
}
更新多個字段

1.使用map
更新多個字段,那麽就要寫成map形式了作為Updates的參數

dt := db.Uic.Table("user")..Where("name = ?" , inputs.Name).Updates(map[string]interface{}{"name": "hello", "im": xxx, "Phone": 182****0534})

2.使用struct來更新多個字段,使用struct更新多個屬性,只會更新這些更改的和非空白字段,也就是說當使用struct更新時,FORM將僅更新具有非空值的字段

dt := db.Uic.Table("user")..Where("name = ?" , inputs.Name).Updates(User{Name: "hello", cnname: xxx})
更新全部字段

使用Save方法來更新所有字段,傳入一個結構體的內存地址,凡是這個結構體的字段,都給更新了。

dt.Save(&user)

好了,到此為止,現學現用,如果還想學期其他功能的同學,可以查看 GORM 中文文檔教程

19 Go的全能ORM簡單入門