I'm trying to figure out how to load associations with gorm
. The documentation is not that great.
I have to models:
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
}
and
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"`
}
So every Account
has a Account Type
associated with it.
When I try loading the data via:
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
}
Could someone please explain how to do this properly the 'gorm way'?