Your Question
gorm有preload的方法,但是有的时候,我已经获取到了model或者model数组,想要加载其中的某个关联字段
比如
type Answer struct {
ID int64 `gorm:"column:id;primaryKey"`
QuestionID int64 `gorm:"column:question_id;index;comment:问题id;not null;default 0"`
Context string `gorm:"column:context;comment:内容"`
AuthorID int64 `gorm:"column:author_id;comment:作者id;not null;default:0"`
CreatedAt time.Time `gorm:"column:created_at;autoCreateTime;comment:创建时间"`
UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime;autoCreateTime;<-:false;comment:更新时间"`
DeletedAt gorm.DeletedAt `gorm:"index"`
Author *user.User `gorm:"foreignKey:ID;references:author_id"`
Question *Question `gorm:"foreignKey:QuestionID"`
}
我已经获取到了as := []Answers,之后我想要加载Author字段,目前我只能使用
if err := q.ormDB.WithContext(ctx).Preload("Author").Order("created_at desc").Find(answers, ids).Error; err != nil {
return err
}
但是这个会增加一次
{"begin":"2021-12-05T18:24:38.063506+08:00","error":null,"level":7,"msg":"orm trace sql","rows":6,"sql":"SELECT * FROM `answers` WHERE `answers`.`id` IN (25,24,23,22,21,20) AND `answers`.`deleted_at` IS NULL ORDER BY created_at desc","time":1234329,"timestamp":"2021-12-05T18:24:38+08:00"}
有没有办法有PostLoad之类的请求?还是我的使用有什么问题?
The document you expected this should be explained
Expected answer
Comment From: ghost
https://gorm.cn/zh_CN/docs/preload.html#%E8%87%AA%E5%AE%9A%E4%B9%89%E9%A2%84%E5%8A%A0%E8%BD%BD-SQL
Comment From: jianfengye
这个还是preload,比如
// AnswersLoadAuthor 批量加载Author字段
func (q *QaService) AnswersLoadAuthor(ctx context.Context, answers *[]*Answer) error {
if answers == nil {
return nil
}
answerColl := collection.NewObjPointCollection(*answers)
ids, err := answerColl.Pluck("ID").ToInt64s()
if err != nil {
return err
}
if len(ids) == 0 {
return nil
}
q.logger.Debug(ctx, "ids", map[string]interface{}{
"ids": ids,
})
if err := q.ormDB.WithContext(ctx).Preload("Author").Order("created_at desc").Find(answers, ids).Error; err != nil {
return err
}
return nil
}
这个函数,参数已经传递了answers了,我只是要填充answers中的Author字段,但是这个sql语句会有两个语句:
select * from answers where id in (1,2,3)
select * from users where id in (11,12,13)
但是里面的第一个sql语句其实我是不想要的,所以我想,已经有了一个ansewers数组了,能不能有一个postload,能只加载Author,就是加载第二个sql语句?
Comment From: ghost
自定义预加载 的SQL 试试呢~
Comment From: jianfengye
自定义预加载 的SQL 试试呢~
能再说的详细一些么?我理解预加载的sql是做不到的
Comment From: ghost
自定义预加载 的SQL 试试呢~
能再说的详细一些么?我理解预加载的sql是做不到的
抱歉,我理解错了,这的确不行。:zipper_mouth_face:
Comment From: github-actions[bot]
This issue has been automatically marked as stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 30 days
Comment From: jinzhu
Maybe we can add a Load function to the Association Mode
Comment From: qeq66
@jinzhu 什么时候可以安排上,急需这个方法