我试图弄清楚如何加载与gorm
的关联。文档不是很好。
我有模特:
type Account struct {
gorm.Model
Name string `gorm:"column:name;unique_index;not null;size:255"`
AccountTypeID uint `gorm:"not null"`
UserID uint `gorm:"not null"`
AccountType accounttypes.AccountType
}
以及
type AccountType struct {
gorm.Model
Name string `gorm:"column:name;unique_index;not null;size:255"`
Type string `gorm:"column:type;unique_index;not null;size:255"`
}
所以每个Account
都有一个关联的Account Type
。
当我尝试通过以下方式加载数据时:
func GetAccounts(userId uint) ([]Account, error) {
db := common.GetDB()
var model []Account
db.LogMode(true)
err := db.Model(&Account{}).Where("accounts.user_id =?", userId).Related(&accounttypes.AccountType{}, "AccountTypes").Error
return model, err
}
以下是输出:
有人能解释一下如何正确地做这件事的'gorm方式'?
1条答案
按热度按时间8i9zcol21#
您可以使用
clause.Associations
,如下所示:www.example.comhttps://gorm.io/docs/preload.html#Preload-Allclause.Associations
可以像Select
一样在创建/更新时与Preload
一起工作,您可以使用它来Preload
所有关联注:
clause.Associations
不会预加载嵌套关联,但您可以将其与Nested Preloading一起使用我还没有测试过,但也许你需要这样的东西:
Where
的情况可能是Where(&Account{UserID: userId})
clause.Associations
可以用于预加载所有关联。如果您想预加载一个项目,有Preload(Item)
方法。在您的情况下:Preload("AccountType")