I have this model:
type User struct {
ID uint
Name string
Age int
Gender string
// hundreds of fields
}
with this hook:
func (m *User) AfterFind(tx *gorm.DB) (err error) {
// I don't know how to get Gender value of APIUser struct from here
return
}
And this smart select struct:
type APIUser struct {
ID uint
Gender string
}
then I run this query:
DB.Model(&User{}).Find(&APIUser{}, id)
Inside AfterFind() hook I want to manipulate retrieved data from database before send them to client, but I couldn't get the value inside this hook. How to do that?
CodePudding user response:
The AfterFind
should be set to both APIUser
and User
Here are sample codes
type User struct {
Id uint64
Avatar string
Nickname string
Password string
}
func (user *User) AfterFind(*gorm.DB) error {
return nil
}
type UserSimple struct {
Id uint64
Avatar string
}
func (v *UserSimple) AfterFind(*gorm.DB) error {
v.Avatar = "prefix/" v.Avatar
return nil
}
us := &UserSimple{}
db.Model(&User{}).Where("id = ?", 123).Find(us)
Output
{123 prefix/avatar}