英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论