2 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
Preload是鏈?zhǔn)椒椒?,Create是finisher方法。只有finisher 方法會(huì)生成并執(zhí)行SQL。
所以...
1 創(chuàng)建書(shū)后按id查找作者
if err ;= database.DB.Create(&book).Error; err != nil {
return err
}
// will not throw not found error
database.DB.Limit(1).Find(&book.Author, book.AuthorID)
ctx.JSON(201, gin.H{"status": "success", "book": book})
2 每次加載作者數(shù)據(jù),使用鉤子
// create and update
// func (b *Book) AfterSave(tx *gorm.DB) (err error) {
// just create
func (b *Book) AfterCreate(tx *gorm.DB) (err error) {
// handle error if you want
tx.Limit(1).Find(&b.Author, b.AuthorID)
return
}
- 2 回答
- 0 關(guān)注
- 222 瀏覽
添加回答
舉報(bào)