英文:
Get smart-select struct's value inside Gorm's AfterFind() hook
问题
我有这个模型:
type User struct {
     ID     uint
     Name   string
     Age    int
     Gender string
     // 其他字段
}
还有这个钩子:
func (m *User) AfterFind(tx *gorm.DB) (err error) {
  // 我不知道如何在这里获取 APIUser 结构体的 Gender 值
  return
}
以及这个智能选择结构体:
type APIUser struct {
  ID     uint
  Gender string
}
然后我运行这个查询:
DB.Model(&User{}).Find(&APIUser{}, id)
在 AfterFind() 钩子中,我想在将数据发送给客户端之前对从数据库检索到的数据进行操作,但是我无法在这个钩子中获取值。如何做到这一点?
英文:
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?
答案1
得分: 1
AfterFind 应该设置为 APIUser 和 User。
以下是示例代码:
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) 
输出结果:
{123 prefix/avatar}
英文:
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}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论