自动将哈希编码数据插入gorm中。

huangapple go评论78阅读模式
英文:

insert hash coded data in gorm automatically

问题

你可以使用GORM的钩子函数来实现在插入或更新数据时自动填充HashID列。钩子函数可以在模型的创建、更新、删除等事件发生时执行自定义的逻辑。

在你的模型中,你可以定义一个BeforeSave钩子函数,它会在保存数据之前被调用。在这个钩子函数中,你可以计算PhoneNumber列的sha256哈希值,并将结果赋值给HashID列。

以下是一个示例代码:

import (
	"crypto/sha256"
	"encoding/hex"
)

type Users struct {
	gorm.Model
	ID          uint   `gorm:"autoIncrement;unique" json:"id"`
	PhoneNumber string `json:"phone_number"`
	HashID      string `gorm:"primaryKey" json:"hash_id"`
	Name        string `gorm:"default:dear user" json:"name"`
	Rank        uint   `json:"rank"`
	Score       uint   `json:"score"`
	Image       string `json:"image"`
	Email       string `json:"email"`
	Address     string `json:"address"`
	Birthday    string `json:"birthday"`
	Biography   string `json:"biography"`
}

func (u *Users) BeforeSave(tx *gorm.DB) (err error) {
	hash := sha256.Sum256([]byte(u.PhoneNumber))
	u.HashID = hex.EncodeToString(hash[:])
	return nil
}

在这个示例中,BeforeSave函数接收一个*gorm.DB参数,你可以在函数中访问数据库事务对象。在函数内部,我们使用sha256包计算PhoneNumber列的哈希值,并使用hex包将其转换为字符串形式。然后,我们将计算得到的哈希值赋值给HashID列。

当你插入或更新数据时,GORM会自动调用BeforeSave函数,并在保存数据之前执行其中的逻辑。这样,HashID列就会被自动填充为PhoneNumber列的sha256哈希值。

希望对你有所帮助!如果你还有其他问题,请随时提问。

英文:

I have a table that represents my user data. There is a field that represents a phone number, and I want to store the hash of that automatically in the database at either update or insert.
so my model is :

type Users struct {
	gorm.Model
	ID          uint          `gorm:"autoIncrement;unique" json:"id"`
	PhoneNumber string        `json:"phone_number"`
	HashID      string        `gorm:"primaryKey" json:"hash_id"`
	Name        string        `gorm:"default:dear user" json:"name"`
	Rank        uint          `json:"rank"`
	Score       uint          `json:"score"`
	Image       string        `json:"image"`
	Email       string        `json:"email"`
	Address     string        `json:"address"`
	Birthday    string        `json:"birthday"`
	Biography   string        `json:"biography"
}

How can I tell the GORM to fill the HashID column with the sha256 hash code of the PhoneNumber column while inserting or updating data?

答案1

得分: 1

你需要这样的代码:

package main

import (
	"crypto/sha256"
	"fmt"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Users struct {
	gorm.Model
	Key  string `json:"phone_number"`
	Hash string `gorm:"primaryKey" json:"hash_id"`
}

func (u *Users) BeforeCreate(tx *gorm.DB) (err error) {
	h := sha256.Sum256([]byte(u.Key))
	u.Hash = fmt.Sprintf("%x", h[:])
	return nil
}

func (u *Users) BeforeSave(tx *gorm.DB) (err error) {
	h := sha256.Sum256([]byte(u.Key))
	u.Hash = fmt.Sprintf("%x", h[:])
	return nil
}

func main() {
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	db.AutoMigrate(&Users{})

	u := Users{Key: "123"}
	db.Create(&u)
}

请查看 https://gorm.io/docs/index.html

英文:

You need something like this:

package main

import (
	"crypto/sha256"

	"fmt"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Users struct {
	gorm.Model
	Key  string `json:"phone_number"`
	Hash string `gorm:"primaryKey" json:"hash_id"`
}

func (u *Users) BeforeCreate(tx *gorm.DB) (err error) {
	h := sha256.Sum256([]byte(u.Key))
	u.Hash = fmt.Sprintf("%x", h[:])
	return nil
}

func (u *Users) BeforeSave(tx *gorm.DB) (err error) {
	h := sha256.Sum256([]byte(u.Key))
	u.Hash = fmt.Sprintf("%x", h[:])
	return nil
}

func main() {
	db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	db.AutoMigrate(&Users{})

	u := Users{Key: "123"}
	db.Create(&u)
}

Check https://gorm.io/docs/index.html

huangapple
  • 本文由 发表于 2021年8月18日 15:59:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/68828561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定